So, here's my custom rake task:
task :backup => :environment do |t|
SeedFu::Writer.write('/path/to/file.rb', class_name: 'Category', constraints: [:id] do |w|
Category.all.each do |x|
w << x
end
end
end
And the following result file contains:
# DO NOT MODIFY THIS FILE, it was auto-generated.
#
# Date: 2014-06-15 21:08:13 +0700
# Seeding Category
# Written with the command:
#
# /home/dave/.rvm/gems/ruby-2.1.2/bin/rake backup
#
Category.seed(:id,
#<Category id: 1, name: "foo">,
#<Category id: 2, name: "bar">,
#<Category id: 3, name: "baz">
)
# End auto-generated file.
Question: Why did the seedfile got commented out?
Thanks!
So, this is a basic string manipulation.
When I read closely on their source code, seed
method accepts Hash
, not object.
So, I simply translated the object to its Hash equivalent:
task :backup => :environment do |t|
SeedFu::Writer.write('/path/to/file.rb', class_name: 'Category', constraints: [:id] do |w|
Category.all.each do |x|
w << x.as_json
end
end
end
Note that you can use .attributes
or .as_json
, but I read somewhere that .attributes
actually takes a lot more time than .as_json
.
After that, I encountered yet another problem: Datetime
columns. When converted to JSON, Datetime columns are not quoted. So what I did was:
- Store the column names (of type
Datetime
) to an array.
- Store current object's
Hash
to a local variable.
- Convert the
Datetime
values to String
, using .to_s
(in the local variable)
- Output the modified local variable to
writer
object.
Hope this helps.
Experiencing exact the same problems, commented output and datetime columns are not quoted. It seems that ActiveSupport::JSON
could kill two birds with one stone.
require 'seed-fu'
j = ActiveSupport::JSON
SeedFu::Writer.write("#{Rails.root}/db/dump_seeds/lectures.rb",{ class_name: 'Lecture', constraints: [:id, :name]}) do |writer|
Lecture.all.order('id').each do |e|
writer << j.decode(j.encode(e))
end
end