Created
April 29, 2009 15:15
-
-
Save fjfish/103834 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# quick class to create seed data from an existing model | |
# http://intridea.com/2008/4/20/seed-fu-simple-seed-data-for-rails | |
# sd = MakeSeedData.new(MyActiveRecord) | |
# sd.generate # get all records | |
# sd.generate(MyActiveRecord.all(:conditions => ...)) | |
# | |
# Generate returns a string, put it in a file in db/fixtures as per their | |
# instructions. It can be passed any array of objects that can pretend to be | |
# the base active records | |
# | |
# You can ignore columns by passing an array of symbols to the initialize | |
# method (defaults to created_at and updated_at) | |
# | |
# Enjoy | |
class MakeSeedData | |
attr_reader :column_names | |
attr_reader :seed_class | |
def initialize(seed_class, except = [:created_at,:updated_at]) | |
@column_names = { } | |
seed_class.columns.each do |col| | |
name = col.name.to_sym | |
@column_names[name] = col.type unless except.include?(name) | |
end | |
@seed_class = seed_class | |
end | |
def generate(scope = nil) | |
output = "" | |
output << "# seed for #{seed_class.name}\n" | |
scope = seed_class.all unless scope | |
scope.each do |row| | |
output << "\n#{seed_class.name}.seed do |s|\n" | |
column_names.each_pair do |name,type| | |
output << " s.#{name.to_s} = #{format_to_type(row[name],type)}\n" | |
end | |
output << "end\n" | |
end | |
output | |
end | |
def format_to_type(value,type) | |
# puts "#{value},#{type}" | |
return "nil" unless value | |
case type | |
when :string, :text | |
escaped_value = value.gsub(/"/,'\"').gsub(/\#\{/,'\#{') | |
"\"#{escaped_value}\"" | |
when :date,:datetime | |
dt = value.to_time | |
"DateTime.new(#{dt.year},#{dt.month},#{dt.day},#{dt.min},#{dt.sec})" | |
else | |
value | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment