Rails Seed-Fu Writer why seed got commented out?

2019-06-03 07:36发布

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!

2条回答
叛逆
2楼-- · 2019-06-03 08:16

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
查看更多
你好瞎i
3楼-- · 2019-06-03 08:37

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:

  1. Store the column names (of type Datetime) to an array.
  2. Store current object's Hash to a local variable.
  3. Convert the Datetime values to String, using .to_s (in the local variable)
  4. Output the modified local variable to writer object.

Hope this helps.

查看更多
登录 后发表回答