Module: AsJsonRepresentations::ClassMethods

Defined in:
lib/as_json_representations.rb

Instance Method Summary collapse

Instance Method Details

#find_representation(name) ⇒ Object



28
29
30
# File 'lib/as_json_representations.rb', line 28

def find_representation(name)
  representations[name] || @parent_entity&.find_representation(name) if name
end

#parent_entityObject



24
25
26
# File 'lib/as_json_representations.rb', line 24

def parent_entity
  @parent_entity
end

#render_representation(object, options) ⇒ Object



32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
# File 'lib/as_json_representations.rb', line 32

def render_representation(object, options)
  representation_name = options.delete(:representation)&.to_sym
  return {} unless (representation = find_representation(representation_name))

  data = {}
  loop do
    data = object.instance_exec(
      options,
      &representation[:block]
    ).merge(data)

    representation =
      if representation[:extend] == true
        representation[:class].parent_entity&.find_representation(representation[:name])
      else
        find_representation(representation[:extend])
      end

    return data unless representation
  end
end

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



5
6
7
8
9
10
11
12
13
14
15
16
17
18
# File 'lib/as_json_representations.rb', line 5

def representation(name, options={}, &block)
  @representations ||= {}
  @representations[name] = options.merge(name: name, class: self, block: block)

  # copy parent representation options that should be inherited
  return unless options[:extend]
  extend_representation_name = options[:extend] == true ? name : options[:extend]
  extend_representation = (parent_entity || self).representations[extend_representation_name]

  %i[includes eager_load].each do |option|
    next unless (extend_option_value = extend_representation[option])
    @representations[name][option] = extend_option_value + (options[option] || [])
  end
end

#representationsObject



20
21
22
# File 'lib/as_json_representations.rb', line 20

def representations
  @representations
end