Class: Hypermodel::Collection

Inherits:
Object
  • Object
show all
Defined in:
lib/hypermodel/collection.rb

Overview

Public: Commands a collection of resources to build themselves in JSON-HAL format, with some links of the collection itself.

Instance Method Summary collapse

Constructor Details

#initialize(collection, controller) ⇒ Collection

Public: Initializes a Collection.

collection - An Array of Mongoid documents. controller - An ActionController instance.

Returns nothing.



14
15
16
17
18
# File 'lib/hypermodel/collection.rb', line 14

def initialize(collection, controller)
  @collection = collection
  @name       = collection.first.class.name.downcase.pluralize
  @controller = controller
end

Instance Method Details

#as_json(*opts) ⇒ Object

Public: Serialize the whole representation as JSON.

Returns a String with the serialization.



23
24
25
# File 'lib/hypermodel/collection.rb', line 23

def as_json(*opts)
  links.update(embedded).as_json(*opts)
end

#embeddedObject

Internal: Constructs the _embedded section of the response.

Returns a Hash of the collection members, decorated as Resources.



42
43
44
45
46
47
48
# File 'lib/hypermodel/collection.rb', line 42

def embedded
  {
    _embedded: {
      @name => decorated_collection
    }
  }
end

Internal: Constructs the _links section of the response.

Returns a Hash of the links of the collection. It will include, at least, a link to itself.



31
32
33
34
35
36
37
# File 'lib/hypermodel/collection.rb', line 31

def links
  _links = parent_link.update({
    self: { href: @controller.polymorphic_url(collection_hierarchy) }
  })

  { _links: _links }
end