Class: Hypermodel::EmptyCollection

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

Overview

Public: Represents an empty Collection.

Instance Method Summary collapse

Constructor Details

#initialize(resource_name, controller) ⇒ EmptyCollection

Public: Initializes a Collection.

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

Returns nothing.



12
13
14
15
# File 'lib/hypermodel/empty_collection.rb', line 12

def initialize(resource_name, controller)
  @name       = resource_name
  @controller = controller
end

Instance Method Details

#as_json(*opts) ⇒ Object

Public: Serialize the whole representation as JSON.

Returns a String with the serialization.



20
21
22
# File 'lib/hypermodel/empty_collection.rb', line 20

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

#embeddedObject

Internal: Constructs an empty _embedded section of the response.

Returns an empty collection.



46
47
48
# File 'lib/hypermodel/empty_collection.rb', line 46

def embedded
  { _embedded: { @name => [] } }
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.



28
29
30
31
32
33
34
35
36
37
38
39
40
41
# File 'lib/hypermodel/empty_collection.rb', line 28

def links
  url = @controller.request.url
  url = url.split('.')[0..-2].join('.') if url =~ /\.\w+$/

  parent_url  = url.split('/')[0..-2].join('/')
  parent_name = parent_url.split('/')[0..-2].last.singularize

  _links = {
    self: { href: url },
    parent_name => { href: parent_url }
  }

  { _links: _links }
end