Module: Roar::JSON::JSONAPI::ForCollection

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

Instance Method Summary collapse

Instance Method Details

#collection_representerObject

FIXME: cache.


24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
# File 'lib/roar/json/json_api.rb', line 24

def collection_representer # FIXME: cache.
  single = self # e.g. Song::Representer

  # this basically does Module.new { include Hash::Collection .. }
  nested_builder.(_base: default_nested_class, _features: [Roar::JSON, Roar::Hypermedia], _block: Proc.new do
    collection :to_a, decorator: single # render/parse every item using the single representer.

    # toplevel links are defined here, as in
    # link(:self) { .. }

    def to_hash(options={})
      hash = super(to_a: options) # [{data: {..}, data: {..}}]
      collection = hash["to_a"]

      document = {data: []}
      included = []
      collection.each do |single|
        document[:data] << single[:data]
        included += single.delete(:included)||[]
      end

      Fragment::Links.(document, Renderer::Links.new.(hash, {}), options)
      Fragment::Included.(document, included, options)
      document
    end
  end)
end

#for_collectionObject

FIXME: same API as representable. TODO: we could use ::collection_representer! here.


52
53
54
# File 'lib/roar/json/json_api.rb', line 52

def for_collection # FIXME: same API as representable. TODO: we could use ::collection_representer! here.
  @collection_representer ||= collection_representer
end