File.open, write and save?

ChuckJHardy picture ChuckJHardy · Feb 15, 2011 · Viewed 89.1k times · Source

I am trying to get a .rb file to make another .rb file within a specific directory with specified content, when that file is run. I dont know whether the best way to do this would be with a Ruby file or a Rake file. You input would be great.

Answer

Simone Carletti picture Simone Carletti · Feb 15, 2011

If you just need to perform a simple script like creating a file, you can simply use a Ruby script without creating a rake task.

# file origin.rb
target  = "target.rb"
content = <<-RUBY
  puts "I'm the target!"
RUBY

File.open(target, "w+") do |f|
  f.write(content)
end

And you can execute the file with

$ ruby origin.rb