Module: Jat::Plugins::SimpleApi::Map::InstanceMethods

Included in:
Jat::Plugins::SimpleApi::Map
Defined in:
lib/jat/plugins/simple_api/lib/map.rb

Constant Summary collapse

EXPOSED_TYPES =
{all: :all, default: :default, none: :none}.freeze

Instance Attribute Summary collapse

Instance Method Summary collapse

Instance Attribute Details

#exposedObject (readonly)

Returns the value of attribute exposed.



39
40
41
# File 'lib/jat/plugins/simple_api/lib/map.rb', line 39

def exposed
  @exposed
end

#fieldsObject (readonly)

Returns the value of attribute fields.



39
40
41
# File 'lib/jat/plugins/simple_api/lib/map.rb', line 39

def fields
  @fields
end

Instance Method Details

#initialize(exposed, fields) ⇒ Object



43
44
45
46
# File 'lib/jat/plugins/simple_api/lib/map.rb', line 43

def initialize(exposed, fields)
  @exposed = EXPOSED_TYPES.fetch(exposed)
  @fields = fields
end

#map_for(serializer, fields, stack = []) ⇒ Object



52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
# File 'lib/jat/plugins/simple_api/lib/map.rb', line 52

def map_for(serializer, fields, stack = [])
  serializer.attributes.each_with_object({}) do |name_attr, result|
    name = name_attr[0]
    attribute = name_attr[1]
    next unless expose?(attribute, fields)

    raise Error, recursive_error_message(stack, name) if stack.any?(name_attr)
    stack << name_attr

    result[name] =
      if attribute.relation?
        nested_serializer = attribute.serializer.call
        nested_fields = fields&.[](name)
        map_for(nested_serializer, nested_fields, stack)
      else
        FROZEN_EMPTY_HASH
      end

    stack.pop
  end
end

#to_hObject



48
49
50
# File 'lib/jat/plugins/simple_api/lib/map.rb', line 48

def to_h
  map_for(self.class.jat_class, fields)
end