module JsonRepresentations::ClassMethods

Public Instance Methods

find_representation(name) click to toggle source
# File lib/json_representations.rb, line 31
def find_representation(name)
  representations[name] || @parent_entity&.find_representation(name) if name
end
parent_entity() click to toggle source
# File lib/json_representations.rb, line 27
def parent_entity
  @parent_entity
end
render_representation(object, representation_name, options) click to toggle source
# 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) click to toggle source
# 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
representations() click to toggle source
# File lib/json_representations.rb, line 23
def representations
  @representations
end