views:

23

answers:

2

I am using ruby on rails. Below given code works. However I was wondering if it can be written better.

  # Usage: write 'hello world' to tmp/hello.txt file
  # Util.write_to_file('hello world', 'a+', 'tmp', 'hello.txt')
  def self.write_to_file(data, mode, *args)
    input = args
    filename = input.pop
    dir = Rails.root.join(*input).cleanpath.to_s
    FileUtils.mkdir_p(dir)
    file = File.join(dir, filename)
    File.open(file, mode) {|f| f.puts(data) }
  end
A: 

You can just leverage the existing API instead of having to do all the dirty work yourself which cleans things up a lot:

def self.write_to_file(data, mode, *path)
  path = File.expand_path(File.join(path.flatten), Rails.root)
  FileUtils.mkdir_p(File.dirname(path))
  File.open(path, mode) do |fh|
    fh.print(data)
  end
end

There's a few things to note here.

  • File.expand_path will resolve any "../" parts to the path.
  • File.dirname is great at determining the directory of an arbitrary file path.
  • Use File#print to write data to a file. File#puts appends a linefeed.
tadman
+1  A: 

How often are you going to be changing the mode? If not very often, I'd put it directly in the method, and do the rest like so:

def self.write_to_file(data, *args)
  file = Rails.root.join(*args)

  FileUtils.mkdir_p(file.dirname)
  File.open(file, "a+") { |f| f.puts(data) }
end
Josh