Class: Gorillib::ModelCollection
- Inherits:
-
Collection
- Object
- Collection
- Gorillib::ModelCollection
- Defined in:
- lib/gorillib/collection/model_collection.rb
Overview
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.
Instance Attribute Summary
Attributes inherited from Collection
Instance Method Summary collapse
-
#as_json(*args) ⇒ Object
same as #to_wire.
-
#initialize(options = {}) ⇒ ModelCollection
constructor
A new instance of ModelCollection.
- #receive_item(label, *args, &block) ⇒ Object
-
#to_json(*args) ⇒ String
JSON serialization of the collection's array representation.
-
#to_wire(options = {}) ⇒ Array
Serializable array representation of the collection.
- #update_or_add(label, attrs, &block) ⇒ Object
Methods inherited from Collection
#<<, #==, #[]=, #add, #each, #inspect, #inspect_compact, #label_for, native?, receive, #receive!, #to_a, #to_hash, #to_s
Constructor Details
#initialize(options = {}) ⇒ ModelCollection
Returns a new instance of ModelCollection.
26 27 28 29 |
# File 'lib/gorillib/collection/model_collection.rb', line 26 def initialize(={}) @item_type = Gorillib::Factory([:item_type]) if [:item_type] super end |
Instance Method Details
#as_json(*args) ⇒ Object
same as #to_wire
55 |
# File 'lib/gorillib/collection/model_collection.rb', line 55 def as_json(*args) to_wire(*args) ; end |
#receive_item(label, *args, &block) ⇒ Object
31 32 33 34 35 |
# File 'lib/gorillib/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) ⇒ String
Returns JSON serialization of the collection's array representation.
57 |
# File 'lib/gorillib/collection/model_collection.rb', line 57 def to_json(*args) to_wire(*args).to_json(*args) ; end |
#to_wire(options = {}) ⇒ Array
Returns serializable array representation of the collection.
51 52 53 |
# File 'lib/gorillib/collection/model_collection.rb', line 51 def to_wire(={}) to_a.map{|el| el.respond_to?(:to_wire) ? el.to_wire() : el } end |
#update_or_add(label, attrs, &block) ⇒ Object
37 38 39 40 41 42 43 44 45 46 47 48 |
# File 'lib/gorillib/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 |