Module: AsJsonRepresentations::ClassMethods

Defined in:
lib/as_json_representations.rb

Instance Method Summary collapse

Instance Method Details

#find_representation(name) ⇒ Object



30
31
32
# File 'lib/as_json_representations.rb', line 30

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

#parent_entityObject



26
27
28
# File 'lib/as_json_representations.rb', line 26

def parent_entity
  @parent_entity
end

#render_representation(object, options) ⇒ Object



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

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



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

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]

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

#representationsObject



22
23
24
# File 'lib/as_json_representations.rb', line 22

def representations
  @representations
end