Class: Hypermodel::Serializers::Mongoid
- Inherits:
-
Object
- Object
- Hypermodel::Serializers::Mongoid
- Defined in:
- lib/hypermodel/serializers/mongoid.rb
Instance Method Summary collapse
- #embedded ⇒ Object
-
#initialize(resource, controller) ⇒ Mongoid
constructor
A new instance of Mongoid.
- #links ⇒ Object
- #to_json(*opts) ⇒ Object
Constructor Details
#initialize(resource, controller) ⇒ Mongoid
Returns a new instance of Mongoid.
4 5 6 7 8 |
# File 'lib/hypermodel/serializers/mongoid.rb', line 4 def initialize(resource, controller) @resource = resource @attributes = resource.attributes.dup @controller = controller end |
Instance Method Details
#embedded ⇒ Object
37 38 39 40 41 42 43 44 45 46 47 |
# File 'lib/hypermodel/serializers/mongoid.rb', line 37 def return {} if .empty? .inject({ _embedded: {} }) do |acc, (name, )| if attributes = (name, ) @attributes.delete(name) acc[:_embedded][name] = attributes end acc end end |
#links ⇒ Object
15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 |
# File 'lib/hypermodel/serializers/mongoid.rb', line 15 def links hash = { self: { href: @controller.polymorphic_url(@resource) } } referenced_relations.each do |name, | = @resource.send(name) relation = .relation if relation == ::Mongoid::Relations::Referenced::In unless .nil? || (.respond_to?(:empty?) && .empty?) hash.update(name => { href: @controller.polymorphic_url() }) end elsif relation == ::Mongoid::Relations::Referenced::Many hash.update(name => { href: @controller.polymorphic_url([@resource, name]) }) else raise "Referenced relation type not implemented: #{relation}" end end { _links: hash } end |
#to_json(*opts) ⇒ Object
10 11 12 13 |
# File 'lib/hypermodel/serializers/mongoid.rb', line 10 def to_json(*opts) attrs = @attributes.update(links).update() attrs.to_json(*opts) end |