Generate Rails fixture skeleton using ActiveRecord
1 2 # Read about fixtures at http://ar.rubyonrails.org/classes/Fixtures.html 3 first: 4 id: 1 5 another: 6 id: 2
As ActiveRecord provides database reflexion features, we can generate a fixture file with all the columns' name prepopulated for number and text types, such as:
1 2 # Read about fixtures at http://ar.rubyonrails.org/classes/Fixtures.html 3 first: 4 id: 1 5 short_title: short_title_first 6 title: title_first
This will be done by the following class:
1 2 require_gem 'activerecord' 3 4 class RailsFixturesGenerator 5 6 def generate(class_name) 7 8 # Get the "Class" object from the class name 9 model_class = Object.const_get(class_name) 10 11 yaml_content = "# Read about fixtures at http://ar.rubyonrails.org/classes/Fixtures.html\n" 12 yaml_content += "first:\n" 13 14 # get if first! 15 model_class.columns.each { |column| 16 17 yaml_content += " " + column.name + ": " 18 19 if column.number? 20 yaml_content += "1" 21 end 22 if column.text? 23 # @todo /!\ max length 24 yaml_content += column.name + "_first" 25 end 26 27 yaml_content += "\n" 28 } 29 30 write_fixture_file(model_class, yaml_content) 31 32 yaml_content 33 end 34 35 # Write the <fixture> yaml file in the test/fixtures folder 36 def write_fixture_file(model_class, yaml_content) 37 38 path = ENV['DEST'] || "#{RAILS_ROOT}/test/fixtures" 39 db = ENV['DB'] || 'test' 40 41 File.open("#{path}/#{model_class.table_name}.yml", 'wb') do |file| 42 file.write yaml_content 43 file.close 44 end 45 end 46 end
Of course, I have an unit test that I wrote before the code ;-)
This was my first "complex" method I wrote in Ruby so please bear with me. Any feedback is welcome. I want to write a Rails plugin in order to share the generators I will write.