Masatoshi Nishiguchi
Software Engineer

Ruby file operations

ruby file rails

Currently working directory

puts "Dir.pwd: #{Dir.pwd}"

Join path

FILE_DIR = "#{Dir.pwd}/test/fixtures/files"
filename = "example.xml"
path     = File.join(FILE_DIR, filename)

Read

contents = File.open("sample.txt", "r") { |file| file.read }
puts contents
file = File.read(path)

Reading multiple files

def read_all_feed_files
  pattern   = File.join(Dir.pwd, "test", "fixtures", "files", "feed_*.xml")
  filenames = Dir.glob(pattern)

  [].tap do |xml_files|
    filenames.each do |io|
      xml_files << File.read(io)
    end
  end
end

Reading each line

File.open("example.rb", "r") do |io|
  io.each_line do |line|
    puts line
  end
end

Reading from URL

require "open-uri"
puts open("https://mnishiguchi.com").read

Reading JSON

data = File.read("#{Rails.root}/test/fixtures/files/feed_a.json")
JSON.parse(data.encode("ASCII", { undef: :replace, replace: "" }))

Write

File.open("data_file.yml", "w") do |io|
  io.write(data)
end
File.write "data_file.yml", data