Class: Hypermodel::Resource

Inherits:
Object
  • Object
show all
Extended by:
Forwardable
Defined in:
lib/hypermodel/resource.rb

Overview

Public: Responsible for building the response in JSON-HAL format. It is meant to be used by Hypermodel::Responder.

In future versions one will be able to subclass it and personalize a Resource for each diffent model, i.e. creating a PostResource.

Instance Method Summary collapse

Constructor Details

#initialize(record, controller) ⇒ Resource

Public: Initializes a Resource.

record - A Mongoid instance of a model. controller - An ActionController instance.

TODO: Detect record type (ActiveRecord, DataMapper, Mongoid, etc..) and choose the corresponding serializer.



25
26
27
28
29
# File 'lib/hypermodel/resource.rb', line 25

def initialize(record, controller)
  @record     = record
  @serializer = Serializer.build(record)
  @controller = controller
end

Instance Method Details

#as_json(*opts) ⇒ Object

Public: Returns a Hash of the resource in JSON-HAL.

opts - Options to pass to the resource as_json.



34
35
36
# File 'lib/hypermodel/resource.rb', line 34

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

#embeddedObject

Internal: Constructs the _embedded section of the response.

Returns a Hash of the embedded resources of the resource.



59
60
61
# File 'lib/hypermodel/resource.rb', line 59

def embedded
  { _embedded: embedded_resources }
end

Internal: Constructs the _links section of the response.

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



42
43
44
45
46
47
48
49
50
51
52
53
54
# File 'lib/hypermodel/resource.rb', line 42

def links
  _links = { self: polymorphic_url(record_with_ancestor_chain(@record)) }

  resources.each do |name, resource|
    _links.update(name => polymorphic_url(record_with_ancestor_chain(resource)))
  end

  sub_resources.each do |sub_resource|
    _links.update(sub_resource => polymorphic_url(record_with_ancestor_chain(@record) << sub_resource))
  end

  { _links: _links }
end

#polymorphic_url(record_or_hash_or_array, options = {}) ⇒ Object

Internal: Returns the url wrapped in a Hash in HAL format.



64
65
66
# File 'lib/hypermodel/resource.rb', line 64

def polymorphic_url(record_or_hash_or_array, options = {})
  { href: @controller.polymorphic_url(record_or_hash_or_array, options = {}) }
end