Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP

Loading…

modified Sequence to accept Enumerators #378

Closed
wants to merge 1 commit into from

2 participants

@spartan-developer

I wanted do be able to do things like

sequence :hour, (1..12).cycle

and thought I'd check it you guys thought it might be useful.
I tried to implement it in a really non-intrusive way.

@joshuaclayton joshuaclayton referenced this pull request from a commit
@joshuaclayton joshuaclayton Sequences support Enumerators
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
7b38221
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Commits on May 12, 2012
  1. @spartan-developer
This page is out of date. Refresh to see the latest.
Showing with 29 additions and 3 deletions.
  1. +16 −2 lib/factory_girl/sequence.rb
  2. +13 −1 spec/factory_girl/sequence_spec.rb
View
18 lib/factory_girl/sequence.rb
@@ -16,13 +16,27 @@ def initialize(name, *args, &proc)
end
def next
- @proc ? @proc.call(@value) : @value
+ @proc ? @proc.call(current_value) : current_value
ensure
- @value = @value.next
+ increment_value
end
def names
[@name] + @aliases
end
+
+ private
+
+ def current_value
+ @value.is_a?(Enumerator) ? @value.peek : @value
+ end
+
+ def increment_value
+ if @value.is_a?(Enumerator)
+ @value.next
+ else
+ @value = @value.next
+ end
+ end
end
end
View
14 spec/factory_girl/sequence_spec.rb
@@ -15,7 +15,7 @@
end
end
- describe "a custom sequence" do
+ describe "a custom sequence with string elements" do
subject { FactoryGirl::Sequence.new(:name, "A") {|n| "=#{n}" } }
its(:next) { should == "=A" }
@@ -25,6 +25,18 @@
end
end
+ describe "a custom sequence with an Enumerator" do
+ subject { FactoryGirl::Sequence.new(:name, %w{foo bar baz}.cycle) {|n| "=#{n}" } }
+ its(:next) { should == "=foo" }
+
+ it "should enumerate properly" do
+ subject.next.should == "=foo"
+ subject.next.should == "=bar"
+ subject.next.should == "=baz"
+ subject.next.should == "=foo"
+ end
+ end
+
describe "a sequence with aliases using default value" do
subject { FactoryGirl::Sequence.new(:test, aliases: [:alias, :other]) { |n| "=#{n}" } }
its(:next) { should == "=1" }
Something went wrong with that request. Please try again.