Sha256: 4e3377a14a9f2f898594e0746bfeea47f4df44a207de99856d1bff652e0c9f1a
Contents?: true
Size: 1.3 KB
Versions: 4
Compression:
Stored size: 1.3 KB
Contents
# require 'pp' module Ampere # Collections are search results from queries. They can be used like arrays, # but you cannot add anything to them. class Collection include Enumerable attr_reader :raw_array attr_reader :model # Instance methods ######################################################## def initialize(model_class, array = []) @raw_array = array @model = model_class end def each @raw_array.each_with_index do |x, i| if x.is_a?(Ampere::Model) then yield(x) else raw_array[i] = @model.find(x) yield(raw_array[i]) end end end # Index into the search results. Lazily loads models when they're accessed. def [](idx) if @raw_array[idx].is_a?(Ampere::Model) then @raw_array[idx] else # This is still an ID. Find it. @raw_array[idx] = @model.find(@raw_array[idx]) end end # Delegates to internal array. def empty? @raw_array.empty? end # Returns the last item. def last self[-1] end def ==(other) if other.is_a?(Array) then to_a == other end end # Class methods ########################################################### end end
Version data entries
4 entries across 4 versions & 1 rubygems
Version | Path |
---|---|
ampere-1.2.3 | lib/ampere/collection.rb |
ampere-1.2.2 | lib/ampere/collection.rb |
ampere-1.2.1 | lib/ampere/collection.rb |
ampere-1.2.0 | lib/ampere/collection.rb |