1
0
Fork 0
mirror of https://github.com/thoughtbot/factory_bot.git synced 2022-11-09 11:43:51 -05:00

Add AttributeAssigner to handle attribute assignment on the build class instance

This commit is contained in:
Joshua Clayton 2011-12-02 16:13:36 -05:00
parent cebabfee96
commit 3eccbc5de0
3 changed files with 45 additions and 14 deletions

View file

@ -4,6 +4,7 @@ require 'factory_girl/proxy'
require 'factory_girl/registry'
require 'factory_girl/null_factory'
require 'factory_girl/factory'
require 'factory_girl/attribute_assigner'
require 'factory_girl/evaluator'
require 'factory_girl/evaluator_class_definer'
require 'factory_girl/attribute'

View file

@ -0,0 +1,38 @@
module FactoryGirl
class AttributeAssigner
attr_reader :evaluator_class_instance
def initialize(build_class, evaluator_class_instance, attribute_names_to_assign = [])
@build_class = build_class
@evaluator_class_instance = evaluator_class_instance
@attribute_names_to_assign = attribute_names_to_assign
@attribute_names_assigned = []
end
def object
build_class_instance.tap do |instance|
(@attribute_names_to_assign - @attribute_names_assigned).each do |attribute|
instance.send("#{attribute}=", get(attribute))
@attribute_names_assigned << attribute
end
end
end
def hash
@attribute_names_to_assign.inject({}) do |result, attribute|
result[attribute] = get(attribute)
result
end
end
private
def build_class_instance
@build_class_instance ||= @build_class.new
end
def get(attribute_name)
@evaluator_class_instance.send(attribute_name)
end
end
end

View file

@ -96,16 +96,11 @@ module FactoryGirl
delegate :set, :attributes, :to => :@evaluator_class_definer
def to_hash
attributes.inject({}) do |result, attribute|
result[attribute] = get(attribute)
result
end
attribute_assigner.hash
end
def object
@object ||= @klass.new
assign_object_attributes
@object
attribute_assigner.object
end
def anonymous_instance
@ -114,16 +109,13 @@ module FactoryGirl
private
def assign_object_attributes
(attributes - @assigned_attributes).each do |attribute|
@assigned_attributes << attribute
@object.send("#{attribute}=", get(attribute))
end
end
def get(attribute)
anonymous_instance.send(attribute)
end
def attribute_assigner
@attribute_assigner ||= AttributeAssigner.new(@klass, anonymous_instance, attributes)
end
end
end
end