Module: AsJsonRepresentations::Collection

Defined in:
lib/as_json_representations/collection.rb

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.included(base) ⇒ Object



7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
# File 'lib/as_json_representations/collection.rb', line 7

def self.included(base)
  base.class_eval do
    def as_json(options={})
      subject = self

      # call supported methods of ActiveRecord::QueryMethods
      i[includes eager_load].each do |method|
        next unless respond_to? method

        args = klass.representations.dig(options[:representation], method)

        # we need to reassign because ActiveRecord returns new object
        subject = subject.public_send(method, args) if args
      end

      return super if respond_to? :super

      subject.map do |item|
        item.respond_to?(:as_json) ? item.as_json(options) : item
      end
    end
  end
end

Instance Method Details

#representation(name, options = {}) ⇒ Object



3
4
5
# File 'lib/as_json_representations/collection.rb', line 3

def representation(name, options={})
  as_json(options.merge(representation: name))
end