Module: JsonRepresentations::ClassMethods

Defined in:
lib/json_representations.rb

Instance Method Summary collapse

Instance Method Details

#find_representation(name) ⇒ Object



31
32
33
# File 'lib/json_representations.rb', line 31

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

#parent_entityObject



27
28
29
# File 'lib/json_representations.rb', line 27

def parent_entity
  @parent_entity
end

#render_representation(object, representation_name, options) ⇒ Object



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

def render_representation(object, representation_name, options)
  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.as_json unless representation
  end
end

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



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

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



23
24
25
# File 'lib/json_representations.rb', line 23

def representations
  @representations
end