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/sequence.rb

63 lines
1 KiB
Ruby
Raw Normal View History

module FactoryBot
2008-06-01 13:46:50 -04:00
# Sequences are defined using sequence within a FactoryBot.define block.
# 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
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) { [] }
if !@value.respond_to?(:peek)
@value = EnumeratorAdapter.new(@value)
end
2008-06-01 13:46:50 -04:00
end
def next(scope = nil)
if @proc && scope
scope.instance_exec(value, &@proc)
elsif @proc
@proc.call(value)
else
value
end
ensure
increment_value
2008-06-01 13:46:50 -04:00
end
2012-04-06 14:41:13 -04:00
def names
[@name] + @aliases
end
private
def value
@value.peek
end
def increment_value
@value.next
end
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