Sha256: 383e20ef454b3fcb31a53d8fe096963807bd2395f46c78bf43e2d8a313067392

Contents?: true

Size: 1.05 KB

Versions: 6

Compression:

Stored size: 1.05 KB

Contents

module ActsAsIcontact
  class ResourceCollection < Enumerator
    attr_reader :total, :retrieved
    
    def initialize(klass, collection, forwardTo=nil)
      @klass = klass
      @forwardTo = forwardTo
      
      @collection = collection[klass.collection_name]
      # Get number of elements
      @retrieved = @collection.size
      @total = collection["total"]
      
      enumcode = Proc.new do |yielder|
        counter = 0
        while counter < @retrieved
          yielder.yield resource(@collection[counter])
          counter += 1
        end
      end
              
      super(&enumcode)
    end
    
    def [](index)
      resource(@collection[index]) if @collection[index]
    end
    
    # Calls "next" to kick off the enumerator.  This is more in line with what users would expect.
    def first
      self.rewind
      self.next
    end
    
    private 
    def resource(properties)
      if @forwardTo
        id = @forwardTo.primary_key
        @forwardTo.find(properties[id])
      else
        @klass.new(properties)
      end
    end
  end
end

Version data entries

6 entries across 6 versions & 2 rubygems

Version Path
SFEley-acts_as_icontact-0.2.3 lib/acts_as_icontact/resource_collection.rb
SFEley-acts_as_icontact-0.2.4 lib/acts_as_icontact/resource_collection.rb
SFEley-acts_as_icontact-0.3.0 lib/acts_as_icontact/resource_collection.rb
acts_as_icontact-0.2.3 lib/acts_as_icontact/resource_collection.rb
acts_as_icontact-0.2.4 lib/acts_as_icontact/resource_collection.rb
acts_as_icontact-0.3.0 lib/acts_as_icontact/resource_collection.rb