2017-10-20 15:20:28 -04:00
|
|
|
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
|
2012-06-25 17:59:48 -04:00
|
|
|
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
|
2013-04-02 07:51:47 -04:00
|
|
|
when 1, -1 then syntax_runner.instance_exec(instance, &block)
|
2012-05-02 00:56:20 -04:00
|
|
|
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
|
|
|
|
|
2011-10-14 22:50:37 -04:00
|
|
|
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
|
|
|
|
|
2012-06-25 17:59:48 -04:00
|
|
|
def ensure_valid_callback_name!
|
2017-10-20 15:20:28 -04:00
|
|
|
unless FactoryBot.callback_names.include?(name)
|
2011-09-16 16:19:42 -04:00
|
|
|
raise InvalidCallbackNameError, "#{name} is not a valid callback name. " +
|
2017-10-20 15:20:28 -04:00
|
|
|
"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
|
2012-05-02 00:56:20 -04:00
|
|
|
|
|
|
|
def syntax_runner
|
|
|
|
@syntax_runner ||= SyntaxRunner.new
|
|
|
|
end
|
2011-09-16 16:06:32 -04:00
|
|
|
end
|
|
|
|
end
|