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:
parent
cebabfee96
commit
3eccbc5de0
3 changed files with 45 additions and 14 deletions
|
@ -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'
|
||||
|
|
38
lib/factory_girl/attribute_assigner.rb
Normal file
38
lib/factory_girl/attribute_assigner.rb
Normal 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
|
|
@ -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
|
||||
|
|
Loading…
Add table
Reference in a new issue