Never been to DZone Snippets before?

Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

About this user

Jean-Michel G http://www.21croissants.eu/

« Newer Snippets
Older Snippets »
Showing 1-1 of 1 total  RSS 

Generate Rails fixture skeleton using ActiveRecord

In Rails 1.1.5, the basic generator generates the following code for the fixture used in database unit tests:
# Read about fixtures at http://ar.rubyonrails.org/classes/Fixtures.html
first:
  id: 1
another:
  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:
# Read about fixtures at http://ar.rubyonrails.org/classes/Fixtures.html
first:
  id: 1
  short_title: short_title_first
  title: title_first


This will be done by the following class:
require_gem 'activerecord'

class RailsFixturesGenerator

  def generate(class_name)
    
    # Get the "Class" object from the class name        
    model_class = Object.const_get(class_name)
    
    yaml_content =  "# Read about fixtures at http://ar.rubyonrails.org/classes/Fixtures.html\n"
    yaml_content += "first:\n"
    
    # get if first!   
    model_class.columns.each { |column|
      
      yaml_content += "  " + column.name + ": "
      
      if column.number?
        yaml_content +=  "1"
      end
      if column.text?
        # @todo /!\ max length
        yaml_content +=  column.name + "_first"
      end
      
      yaml_content += "\n"      
    }  
    
    write_fixture_file(model_class, yaml_content)
    
    yaml_content            
  end  
  
  # Write the <fixture> yaml file  in the test/fixtures folder
  def write_fixture_file(model_class, yaml_content)
    
    path = ENV['DEST'] || "#{RAILS_ROOT}/test/fixtures"
    db   = ENV['DB']   || 'test'
    
    File.open("#{path}/#{model_class.table_name}.yml", 'wb') do |file|    
      file.write yaml_content 
      file.close    
    end
  end
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.
« Newer Snippets
Older Snippets »
Showing 1-1 of 1 total  RSS