mirror of
https://github.com/thoughtbot/factory_bot.git
synced 2022-11-09 11:43:51 -05:00

This introduces an EnumeratorAdapter so everything coming in looks like an Enumerator. It doesn't use the adapter if the #peek method exists on the object. This allows for sequences like: sequence(:cities, %w[Boston Atlanta Detroit Seattle].cycle) This also makes it easier to cycle through arrays and ranges, since they can be converted to Enumerators rather easily. sequence(:month, (1..12).to_enum) sequence(:month, %w[foo bar baz].to_enum) This doesn't handle when calling Range#step out of the box, because Ruby returns an Enumerator but ActiveSupport 3.x returns an array, meaning #to_enum still needs to be called. Closes #339, #378
48 lines
873 B
Ruby
48 lines
873 B
Ruby
module FactoryGirl
|
|
|
|
# Sequences are defined using sequence within a FactoryGirl.define block.
|
|
# Sequence values are generated using next.
|
|
# @api private
|
|
class Sequence
|
|
attr_reader :name
|
|
|
|
def initialize(name, *args, &proc)
|
|
@name = name
|
|
@proc = proc
|
|
|
|
options = args.extract_options!
|
|
@value = args.first || 1
|
|
@aliases = options.fetch(:aliases) { [] }
|
|
|
|
if !@value.respond_to?(:peek)
|
|
@value = EnumeratorAdapter.new(@value)
|
|
end
|
|
end
|
|
|
|
def next
|
|
@proc ? @proc.call(@value.peek) : @value.peek
|
|
ensure
|
|
@value.next
|
|
end
|
|
|
|
def names
|
|
[@name] + @aliases
|
|
end
|
|
|
|
private
|
|
|
|
class EnumeratorAdapter
|
|
def initialize(value)
|
|
@value = value
|
|
end
|
|
|
|
def peek
|
|
@value
|
|
end
|
|
|
|
def next
|
|
@value = @value.next
|
|
end
|
|
end
|
|
end
|
|
end
|