Permalink
Browse files

Implement Relation#each_with_index

  • Loading branch information...
1 parent 49b1402 commit 6025e78284cb4f129b6b8a65c88d824b1c627e72 @nathansobo committed May 25, 2011
View
@@ -3,7 +3,7 @@ source "http://www.rubygems.org"
gemspec
gem 'rspec', '2.5'
-gem 'rr', '>= 1.0'
+gem 'rr', '1.0'
gem 'pg'
gem 'differ'
gem 'machinist'
View
@@ -3,7 +3,7 @@ class Record < Tuple
class << self
delegate :all, :update, :dataset, :count, :[], :to_update_sql, :to_sql, :get_column, :first, :empty?, :find,
:clear, :where, :where_any, :join, :join_through, :left_join, :project, :group_by, :order_by, :limit,
- :offset, :tables, :synthetic_columns, :wire_representation, :to => :relation
+ :offset, :tables, :synthetic_columns, :wire_representation, :each, :each_with_index, :to => :relation
def table
relation
@@ -3,7 +3,7 @@ module Relations
class Relation
extend EqualityDerivation
- delegate :to_sql, :dataset, :all, :first, :count, :size, :each, :empty?, :to => :query
+ delegate :to_sql, :dataset, :all, :first, :count, :size, :each, :each_with_index, :empty?, :to => :query
def query(parent=nil)
query_class.new(self, parent).build
View
@@ -31,6 +31,12 @@ def each
end
end
+ def each_with_index
+ dataset.each_with_index do |field_values, index|
+ yield tuple_builder.build_tuple(field_values), index
+ end
+ end
+
def first
r = dataset
r.empty? ? nil : tuple_builder.build_tuple(r.first)
View
@@ -18,8 +18,8 @@ Gem::Specification.new do |s|
s.add_dependency('activesupport', '>= 3.0.4')
s.add_dependency('sequel', '>= 3.20.0')
- s.add_development_dependency 'rspec', '>= 2.5'
- s.add_development_dependency 'rr', '>= 1.0'
+ s.add_development_dependency 'rspec', '2.5'
+ s.add_development_dependency 'rr', '1.0'
s.add_development_dependency 'pg'
s.add_development_dependency 'differ'
s.add_development_dependency 'machinist'
@@ -28,6 +28,23 @@ class Post < Record
end
end
+ describe "#each_with_index" do
+ it "iterates over records in the relation with an index" do
+ DB[:blogs] << { :id => 1, :title => "Blog 1" }
+ DB[:blogs] << { :id => 2, :title => "Blog 2" }
+
+ records = []
+ indices = []
+ Blog.order_by(:id).each_with_index do |record, index|
+ records.push(record)
+ indices.push(index)
+ end
+
+ records.should == [Blog.find(1), Blog.find(2)]
+ indices.should == [0, 1]
+ end
+ end
+
describe "#find" do
before do
DB[:blogs] << { :id => 1, :title => "Blog 1" }

0 comments on commit 6025e78

Please sign in to comment.