0

I am trying to take the content of a CSV file, then use these contents to generate another file.

The approach I've taken is to import my data into a model (http://railscasts.com/episodes/396-importing-csv-and-excel).

Now I want to take the data from the database and create a text file.

I've created a Ruby file using:

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

I can't work out how to fill 'content' with the data from my data model.

Any suggestions?

the Tin Man
  • 158,662
  • 42
  • 215
  • 303

2 Answers2

0

First, let's look at the code you've written. It could all be reduced to:

content = "test"
File.write("target.rb", content)

Expanding it a little and making it more idiomatic:

content = "test"
File.open("target.rb", "w") do |f|
  f.write(content)
end
  • Don't use 'w+' for your file mode UNLESS you understand why you need it. Instead use w, which is "write-only" and is sufficient for normal file writing/creation.
  • There's no need to assign the name of the file to a variable, then use that variable for the parameter to File.open. Just use the literal name there; Avoid unnecessary variable assignments unless you need to use it more than once. (And consider using constants if you're using a literal assignment more than once.)

There is no sample input, or an example of your desired output in your question, so it's really hard to address the CSV aspect of the question; As is, there's nothing in the question to do with CSV. Ruby's CSV class is nicely documented though, and has examples covering the normal day-to-day stuff.

the Tin Man
  • 158,662
  • 42
  • 215
  • 303
0

My reputation is not high enough to ask you more questions about your requirements via comments, but here are a few facts that might help.

I am assuming that you have populated a Rails model with the information you need. I have no sample code from you so I'll provide an example with a 'Book' model. The Book model has a title and an author, both of type String.

target = "file.txt"
contents = ""

# Get all books as an array. Arrays have iterators so we can use 'each'
Book.all.each do |book|
  # get the book title, append it to the string. Add a newline
  contents.concat(book.title).concat($/)

  # get the book author
  contents.concat(book.author).concat($/)

  # Just a line separator 
  contents.concat("-----").concat($/)
end
File.open(target, "w").write(contents)

The above would yield something like this inside the text file:

Book 1
Author 1
-----
Book 2
Author 1
-----
...

Reading up more on the Rails active records might help you as well: ActiveRecord

alcoholtech
  • 180
  • 1
  • 5