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.



29
30
31
# File 'lib/jat/plugins/simple_api/lib/map.rb', line 29

def exposed
  @exposed
end

#fieldsObject (readonly)

Returns the value of attribute fields.



29
30
31
# File 'lib/jat/plugins/simple_api/lib/map.rb', line 29

def fields
  @fields
end

Instance Method Details

#initialize(exposed, fields) ⇒ Object



33
34
35
36
# File 'lib/jat/plugins/simple_api/lib/map.rb', line 33

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

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



42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
# File 'lib/jat/plugins/simple_api/lib/map.rb', line 42

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



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

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