Module: Roar::JSON::JSONAPI::Declarative

Defined in:
lib/roar/json/json_api.rb

Overview

New API for JSON-API representers.

Instance Method Summary collapse

Instance Method Details

#has_many(name, options = {}, &block) ⇒ Object


105
106
107
# File 'lib/roar/json/json_api.rb', line 105

def has_many(name, options={}, &block)
  has_one(name, options.merge(collection: true), &block)
end

#has_one(name, options = {}, &block) ⇒ Object


75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
# File 'lib/roar/json/json_api.rb', line 75

def has_one(name, options={}, &block)
  # every nested representer is a full-blown JSONAPI representer.
  dfn = nil

  nested(:included, inherit: true) do
    dfn = property(name, collection: options[:collection]) do
      include Roar::JSON::JSONAPI
      include Roar::JSON
      include Roar::Hypermedia

      instance_exec(&block)

      def from_document(hash)
        hash
      end
    end
  end

  property_representer = Class.new(dfn[:extend].(nil))
  property_representer.class_eval do
    def to_hash(options)
      super(include: [:type, :id, :links])
    end
  end

  nested(:relationships, inherit: true) do # FIXME: make that a bit nicer readable and document what i'm doing here.
    property(name, options.merge(decorator: property_representer))
  end
end

66
67
68
69
# File 'lib/roar/json/json_api.rb', line 66

def link(name, options={}, &block)
  return super(name, &block) unless options[:toplevel]
  for_collection.link(name, &block)
end

#meta(&block) ⇒ Object


71
72
73
# File 'lib/roar/json/json_api.rb', line 71

def meta(&block)
  representable_attrs[:meta_representer] = Class.new(Roar::Decorator, &block)
end

#type(name = nil) ⇒ Object


59
60
61
62
63
64
# File 'lib/roar/json/json_api.rb', line 59

def type(name=nil)
  return @type unless name # original name.

  heritage.record(:type, name)
  @type = name.to_s
end