Skip to content

Commit

Permalink
Make Collections enumerable.
Browse files Browse the repository at this point in the history
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
Derek Lindahl committed Jun 12, 2012
1 parent 30dc770 commit 412dfff
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 17 deletions.
14 changes: 7 additions & 7 deletions 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
Expand All @@ -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
Expand All @@ -45,6 +41,10 @@ def reload
@records = process_records!
end

def __getobj__
@records
end

protected

# Converts all valid raw data hashes into mapped records
Expand Down
18 changes: 8 additions & 10 deletions test/collection_test.rb
Expand Up @@ -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
Expand Down

0 comments on commit 412dfff

Please sign in to comment.