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

68 lines
1.7 KiB
Ruby
Raw Normal View History

2012-05-05 10:53:05 -04:00
require 'active_support/core_ext/hash/except'
require 'active_support/core_ext/class/attribute'
2012-01-03 09:31:40 -05:00
module FactoryGirl
2012-05-05 02:31:31 -04:00
# @api private
class Evaluator
class_attribute :attribute_lists
2012-01-03 09:31:40 -05:00
private_instance_methods.each do |method|
undef_method(method) unless method =~ /^__|initialize/
end
def initialize(build_class, build_strategy, overrides = {})
@build_class = build_class
@build_strategy = build_strategy
2011-12-16 14:27:38 -05:00
@overrides = overrides
@cached_attributes = overrides
@overrides.each do |name, value|
singleton_class.define_attribute(name) { value }
end
end
delegate :new, to: :@build_class
def association(factory_name, overrides = {})
strategy_override = overrides.fetch(:strategy) { :create }
runner = FactoryRunner.new(factory_name, strategy_override, [overrides.except(:strategy)])
@build_strategy.association(runner)
end
def instance=(object_instance)
@instance = object_instance
end
def method_missing(method_name, *args, &block)
if @instance.respond_to?(method_name)
@instance.send(method_name, *args, &block)
else
SyntaxRunner.new.send(method_name, *args, &block)
end
end
def __override_names__
@overrides.keys
end
2012-05-05 00:53:19 -04:00
def self.attribute_list
AttributeList.new.tap do |list|
attribute_lists.each do |attribute_list|
list.apply_attributes attribute_list.to_a
end
end
end
def self.define_attribute(name, &block)
define_method(name) do
if @cached_attributes.key?(name)
@cached_attributes[name]
else
@cached_attributes[name] = instance_exec(&block)
end
end
end
end
end