Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
Browse files

Make Collections enumerable.

This uses delegation to call unknown Collection methods on the records attribute which allows the full use of all enumerable methods on a collection without re-implementing them by hand.
  • Loading branch information...
commit 412dfffc0d3c6b74c36926ee37279fa26045162e 1 parent 30dc770
@dlindahl dlindahl authored
Showing with 15 additions and 17 deletions.
  1. +7 −7 lib/sheet_mapper/collection.rb
  2. +8 −10 test/collection_test.rb
View
14 lib/sheet_mapper/collection.rb
@@ -1,7 +1,9 @@
+require 'delegate'
+
module SheetMapper
class CollectionNotFound < StandardError; end
- class Collection
+ class Collection < SimpleDelegator
attr_reader :records, :worksheet
# spreadsheet is a SheetMapper::Spreadsheet
@@ -13,12 +15,6 @@ def initialize(spreadsheet, worksheet)
@records = process_records!
end
- # Each block for every mapped record
- # @collection.each { |m| ...mapped obj... }
- def each(&block)
- records.each(&block)
- end
-
# Returns an array of mapped records
# @collection.rows => [<SheetMapper::Base>, ...]
def rows
@@ -45,6 +41,10 @@ def reload
@records = process_records!
end
+ def __getobj__
+ @records
+ end
+
protected
# Converts all valid raw data hashes into mapped records
View
18 test/collection_test.rb
@@ -33,20 +33,18 @@ def changed?; true; end
end
end # worksheet
- context "for each method" do
- setup do
+ context "Enumerability" do
+ subject do
@collection = SheetMapper::Collection.new(@spreadsheet, @worksheet)
end
- should "support iterating each mapped row" do
- rows = []
- @collection.each { |c| rows << c }
- assert_equal 3, rows.size
- assert_equal ["Bob", 21], rows[0].tuple
- assert_equal ["Susan", 34], rows[1].tuple
- assert_equal ["Joey", 67], rows[2].tuple
+ should "behave like an Enumerable" do
+ assert_equal subject.first, subject.records.first
+ assert subject.respond_to?(:each)
+ assert subject.respond_to?(:find)
+ assert subject.respond_to?(:map)
end
- end # each
+ end # enum
context "for rows method" do
setup do
Please sign in to comment.
Something went wrong with that request. Please try again.