Rails Seed-Fu Writer why seed got commented out?

前提是你 提交于 2019-12-23 02:38:27

问题


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!


回答1:


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.




回答2:


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


来源:https://stackoverflow.com/questions/24230462/rails-seed-fu-writer-why-seed-got-commented-out

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!