# Adapted from http://snippets.dzone.com/posts/show/2389 class FixtureRevert def self.revert(class_name) # Get the "Class" object from the class name model_class = class_name.is_a?(String) ? Object.const_get(class_name) : class_name return "Only ActiveRecord objects are supported" unless check_for_ar(model_class) yaml_content = "# Read about fixtures at http://ar.rubyonrails.org/classes/Fixtures.html\n" yaml_content += "one:\n" # get if first! model_class.columns.each { |column| yaml_content += " " + column.name + ": " yaml_content += contents_for_column(column) yaml_content += "\n" } if write_fixture_file(model_class, yaml_content) puts "Fixture for #{model_class.to_s} has been generated" else puts "Fixture revert for #{model_class.to_s} was canceled" end end # Write the yaml file in the test/fixtures folder def self.write_fixture_file(model_class, yaml_content) path = ENV['DEST'] || "#{RAILS_ROOT}/test/fixtures" db = ENV['DB'] || 'test' if File.exists?("#{path}/#{model_class.table_name}.yml") print "Fixture for #{model_class.to_s} already exists, overwrite? [yn]" return false if $stdin.gets.chomp =~ /n/ end File.open("#{path}/#{model_class.table_name}.yml", 'wb') do |file| file.write yaml_content file.close end return true end def self.contents_for_column(column) return column.default.to_s if column.default content = case column.type when :integer then "1" when :string then "I like turtles" when :text then "This is a longer description of why I like turtles" when :boolean then "true" when :datetime then "<%= (Time.now - 100).to_s(:db) %>" when :decimal then "0.0" when :float then "1.1" when :time then "<%= (Time.now - 100).to_s(:db) %>" when :date then "<%= (Date.today - 1).to_s(:db) %>" else "I have no clue" end return content end def self.check_for_ar(model) model.ancestors.include?(ActiveRecord::Base) end end