public
Description: FixtureReplacement rails plugin (version 2 and on)
Homepage: http://replacefixtures.rubyforge.org/
Clone URL: git://github.com/smtlaissezfaire/fixturereplacement.git
smt (author)
Sun Mar 09 21:59:13 -0700 2008
commit  975addf30b17205ca218ae0acc6cd77a6f7fcbab
tree    9717db4eaca89c7766ed1aa33300b6b2ede7de19
parent  5c16b52168e61e1642b77b2db646ae070287d110
fixturereplacement / lib / fixture_replacement / controller / active_record_factory.rb
100644 62 lines (51 sloc) 1.666 kb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
module FixtureReplacementController
  # I am a Factory which creates ActiveRecord Class instances.
  # Give me a collection of attributes, and an additional hash,
  # and I will merge them into a new ActiveRecord Instance (either a new
  # instance with ActiveRecord::Base#new, or a created one ActiveRecord::Base#create!).
  class ActiveRecordFactory
    
    def initialize(attributes, hash={}, original_caller=self)
      @attributes = attributes
      @hash_given_to_constructor = hash
      @caller = original_caller
    end
    
    def to_new_instance
      new_object = @attributes.active_record_class.new
      assign_values_to_instance new_object
      return new_object
    end
    
    def to_created_instance
      created_obj = self.to_new_instance
      created_obj.save!
      return created_obj
    end
 
  protected
  
    def hash_given_to_constructor
      @hash_given_to_constructor || Hash.new
    end
    
  private
 
    def assign_values_to_instance(instance_object)
      all_attributes.each do |key, value|
        value = evaluate_possible_delayed_proc(value)
        instance_object.__send__("#{key}=", value)
      end
    end
 
    def evaluate_possible_delayed_proc(value)
      case value
      when Array
        value.map! { |element| evaluate_possible_delayed_proc element }
      when ClassFactory.delayed_evaluation_proc
        value.evaluate(@caller)
      else
        value
      end
    end
    
    def all_attributes
      @attributes.merge!
      @all_merged_attributes ||= attributes_hash.merge(self.hash_given_to_constructor)
    end
    
    def attributes_hash
      @attributes.hash
    end
    
  end
end