TIL: exporting from Rails console to a file
I was looking to export a large Ruby object to a .rb
file.
I found a few tips on exporting to .csv
from this site:
require 'csv'
file = "#{Rails.root}/public/user_data.csv"
products = Product.order(:first_name)
headers = ["Product ID", "Name", "Price", "Description"]
CSV.open(file, 'w', write_headers: true, headers: headers) do |writer|
products.each do |product|
writer << [product.id, product.name, product.price, product.description]
end
end
And eventually found what I was looking for: a simple way to export to any File
object. Thanks to this SO solution.
irb:001> f = File.new('statements.rb', 'w')
irb:002> f << Account.find(1)
irb:003> f.close