File.open, write and save?
Asked Answered
G

3

39

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.

Gosplan answered 15/2, 2011 at 20:18 Comment(0)
G
19

This turned out to be the best solution.

File.open("linecount.txt",'w') do |filea|
  File.open("testfile.txt",'r') do |fileb|
    while line = fileb.gets
      filea.puts line.length
    end
  end
end
Gosplan answered 28/2, 2011 at 7:54 Comment(2)
Within a rails project - where would you place the linecount.txt file?Haustellum
Where should I write this code ? i have same requirement but i dont know where should i write this code and execute thisBackwater
R
45

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
Reneta answered 15/2, 2011 at 20:29 Comment(1)
I think you can also use puts instead of writeMinoan
D
25
directory = "../../directory"
File.open(File.join(directory, 'file.rb'), 'w') do |f|
  f.puts "contents"
end
Document answered 15/2, 2011 at 20:22 Comment(2)
Thanks Dogbert - if I had more complex content, like a few methods with constants which can be placed within a string, how would I go about it.Gosplan
What format do you have the content in? How are you getting/generating the content?Document
G
19

This turned out to be the best solution.

File.open("linecount.txt",'w') do |filea|
  File.open("testfile.txt",'r') do |fileb|
    while line = fileb.gets
      filea.puts line.length
    end
  end
end
Gosplan answered 28/2, 2011 at 7:54 Comment(2)
Within a rails project - where would you place the linecount.txt file?Haustellum
Where should I write this code ? i have same requirement but i dont know where should i write this code and execute thisBackwater

© 2022 - 2024 — McMap. All rights reserved.