class Gorillib::ModelCollection
A collection of Models
### Item Type
‘item_type` is a class attribute – you can make a “collection of Foo’s” by subclassing ModelCollection
and set the item item_type at the class level:
class ClusterCollection < ModelCollection self.item_type = Cluster end
A model collection serializes as an array does, but indexes labelled objects as a hash does.
Public Class Methods
new(options={})
click to toggle source
Calls superclass method
Gorillib::Collection::new
# File lib/gorillib/model/collection/model_collection.rb, line 26 def initialize(options={}) @item_type = Gorillib::Factory(options[:item_type]) if options[:item_type] super end
Public Instance Methods
as_json(*args)
click to toggle source
same as to_wire
# File lib/gorillib/model/collection/model_collection.rb, line 55 def as_json(*args) to_wire(*args) ; end
receive_item(label, *args, &block)
click to toggle source
Calls superclass method
Gorillib::Collection#receive_item
# File lib/gorillib/model/collection/model_collection.rb, line 31 def receive_item(label, *args, &block) item = item_type.receive(*args, &block) super(label, item) rescue StandardError => err ; err.polish("#{item_type} #{label} as #{args.inspect} to #{self}") rescue nil ; raise end
to_json(*args)
click to toggle source
@return [String] JSON serialization of the collection’s array representation
# File lib/gorillib/model/collection/model_collection.rb, line 57 def to_json(*args) to_wire(*args).to_json(*args) ; end
to_wire(options={})
click to toggle source
@return [Array] serializable array representation of the collection
# File lib/gorillib/model/collection/model_collection.rb, line 51 def to_wire(options={}) to_a.map{|el| el.respond_to?(:to_wire) ? el.to_wire(options) : el } end
update_or_add(label, attrs, &block)
click to toggle source
# File lib/gorillib/model/collection/model_collection.rb, line 37 def update_or_add(label, attrs, &block) if label && include?(label) item = fetch(label) item.receive!(attrs, &block) item else attrs = attrs.attributes if attrs.is_a? Gorillib::Model attrs = attrs.merge(key_method => label) if key_method && label receive_item(label, attrs, &block) end rescue StandardError => err ; err.polish("#{item_type} #{label} as #{attrs} to #{self}") rescue nil ; raise end