Fixtures is a fancy word for ‘sample data’. Fixtures allow you to populate your database with predefined data. Fixtures are typically used during testing or when providing initial data (bootstrap data) for a live application.

A Fixture is a collection (Hash) of objects.

Methods
Attributes
[RW] klass The class that the Fixtures refer to.
[RW] name The name of this Fixture.
[RW] objects Used to keep the order.
Public Class methods
new(klass, options = { } )
    # File lib/og/fixture.rb, line 69
69:   def initialize(klass, options = { } )
70:     @klass = klass
71:     @name = class_to_name(klass)
72:     @objects = []    
73:     load(options[:root_dir] || options[:root] || Fixtures.root_dir)
74:   end
Public Instance methods
load(root_dir = Fixtures.root_dir)
    # File lib/og/fixture.rb, line 76
76:   def load(root_dir = Fixtures.root_dir)
77:     raise("The fixture root directory '#{root_dir}' doesn't exits") unless File.exist?(root_dir)
78: 
79:     if path = "#{root_dir}/#{@name}.yml" and File.exist?(path)
80:       parse_yaml(path)
81:     end
82: 
83:     if path = "#{root_dir}/#{@name}.yaml" and File.exist?(path)
84:       parse_yaml(path)
85:     end
86:     
87:     if path = "#{root_dir}/#{@name}.csv" and File.exist?(path)
88:       parse_csv(path)
89:     end
90:     
91:     return self
92:   end
parse_csv(path)

Parse a fixture file in CSV format. Many RDBM systems and Spreadsheets can export to CVS, so this is a rather useful format.

     # File lib/og/fixture.rb, line 118
118:   def parse_csv(path)
119:     require 'csv'
120: 
121:     str = Nitro::Template.new.render(File.read(path))
122:     
123:     reader = CSV::Reader.create(str)
124:     header = reader.shift
125: 
126:     reader.each_with_index do |row, i|
127:       data = {}
128:       row.each_with_index do |cell, j| 
129:         data[header[j].to_s.strip] = cell.to_s.strip 
130:       end
131:       self["#{@name}_#{i+1}"] = obj = instantiate(data)
132:       @objects << obj
133:     end
134:   end
parse_yaml(path)

Parse a fixture file in YAML format.

     # File lib/og/fixture.rb, line 96
 96:   def parse_yaml(path)
 97:     require 'yaml'
 98: 
 99:     str = Nitro::Template.new.render(File.read(path))
100:     
101:     if yaml = YAML::load(str)
102:       for name, data in yaml
103:         self[name] = instantiate(data)
104:       end
105:     end
106: 
107:     # sort the objects.
108:         
109:     str.scan(/^(\w*?):$/).each do |key|
110:       @objects << self[key.to_s]
111:     end
112:   end