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_bot/callback.rb

41 lines
936 B
Ruby
Raw Normal View History

module FactoryBot
2011-09-16 16:06:32 -04:00
class Callback
2012-04-23 23:16:22 -04:00
attr_reader :name
2011-09-16 16:06:32 -04:00
def initialize(name, block)
@name = name.to_sym
@block = block
ensure_valid_callback_name!
2011-09-16 16:19:42 -04:00
end
2011-12-06 00:20:37 -05:00
def run(instance, evaluator)
2011-09-16 16:24:16 -04:00
case block.arity
when 1, -1 then syntax_runner.instance_exec(instance, &block)
when 2 then syntax_runner.instance_exec(instance, evaluator, &block)
else syntax_runner.instance_exec(&block)
2011-09-16 16:24:16 -04:00
end
end
def ==(other)
name == other.name &&
block == other.block
end
2012-04-23 23:16:22 -04:00
protected
attr_reader :block
2011-09-16 16:19:42 -04:00
private
def ensure_valid_callback_name!
unless FactoryBot.callback_names.include?(name)
2011-09-16 16:19:42 -04:00
raise InvalidCallbackNameError, "#{name} is not a valid callback name. " +
"Valid callback names are #{FactoryBot.callback_names.inspect}"
2011-09-16 16:19:42 -04:00
end
2011-09-16 16:06:32 -04:00
end
def syntax_runner
@syntax_runner ||= SyntaxRunner.new
end
2011-09-16 16:06:32 -04:00
end
end