2017-10-20 15:20:28 -04:00
|
|
|
module FactoryBot
|
2008-06-01 13:46:50 -04:00
|
|
|
|
2017-10-20 15:20:28 -04:00
|
|
|
# Sequences are defined using sequence within a FactoryBot.define block.
|
2011-01-26 20:55:06 -05:00
|
|
|
# Sequence values are generated using next.
|
2012-05-05 02:31:31 -04:00
|
|
|
# @api private
|
2008-06-01 13:46:50 -04:00
|
|
|
class Sequence
|
2012-04-06 14:41:13 -04:00
|
|
|
attr_reader :name
|
2011-05-19 10:56:45 -04:00
|
|
|
|
2012-05-05 02:31:31 -04:00
|
|
|
def initialize(name, *args, &proc)
|
2012-04-06 14:41:13 -04:00
|
|
|
@name = name
|
|
|
|
@proc = proc
|
|
|
|
|
|
|
|
options = args.extract_options!
|
|
|
|
@value = args.first || 1
|
2012-05-05 01:14:21 -04:00
|
|
|
@aliases = options.fetch(:aliases) { [] }
|
2012-05-13 01:54:41 -04:00
|
|
|
|
|
|
|
if !@value.respond_to?(:peek)
|
|
|
|
@value = EnumeratorAdapter.new(@value)
|
|
|
|
end
|
2008-06-01 13:46:50 -04:00
|
|
|
end
|
|
|
|
|
2013-01-11 12:05:17 -05:00
|
|
|
def next(scope = nil)
|
|
|
|
if @proc && scope
|
|
|
|
scope.instance_exec(value, &@proc)
|
|
|
|
elsif @proc
|
|
|
|
@proc.call(value)
|
|
|
|
else
|
|
|
|
value
|
|
|
|
end
|
2010-08-12 22:42:18 -04:00
|
|
|
ensure
|
2013-01-11 12:05:17 -05:00
|
|
|
increment_value
|
2008-06-01 13:46:50 -04:00
|
|
|
end
|
2012-04-06 14:41:13 -04:00
|
|
|
|
|
|
|
def names
|
|
|
|
[@name] + @aliases
|
|
|
|
end
|
2012-05-13 01:54:41 -04:00
|
|
|
|
|
|
|
private
|
|
|
|
|
2013-01-11 12:05:17 -05:00
|
|
|
def value
|
|
|
|
@value.peek
|
|
|
|
end
|
|
|
|
|
|
|
|
def increment_value
|
|
|
|
@value.next
|
|
|
|
end
|
|
|
|
|
2012-05-13 01:54:41 -04:00
|
|
|
class EnumeratorAdapter
|
|
|
|
def initialize(value)
|
|
|
|
@value = value
|
|
|
|
end
|
|
|
|
|
|
|
|
def peek
|
|
|
|
@value
|
|
|
|
end
|
|
|
|
|
|
|
|
def next
|
|
|
|
@value = @value.next
|
|
|
|
end
|
|
|
|
end
|
2008-06-01 13:46:50 -04:00
|
|
|
end
|
|
|
|
end
|