Class: JSONAPIHelpers::Serializers::Data

Inherits:
Object
  • Object
show all
Defined in:
lib/jsonapi_helpers/serializers/data.rb

Instance Method Summary collapse

Constructor Details

#initialize(id:, type:, attributes: {}, meta: {}, relationships: nil, key_transform: JSONAPIHelpers.config.key_transform) ⇒ Data

Returns a new instance of Data.



9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
# File 'lib/jsonapi_helpers/serializers/data.rb', line 9

def initialize(
  id:,
  type:,
  attributes: {},
  meta: {},
  relationships: nil,
  key_transform: JSONAPIHelpers.config.key_transform
)
  @id = id
  @type = type
  @attributes = attributes
  @meta = meta
  @relationships = relationships
  @key_transform = key_transform
end

Instance Method Details

#to_h(shallow: false) ⇒ Object



25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
# File 'lib/jsonapi_helpers/serializers/data.rb', line 25

def to_h(shallow: false)
  data = {
    id: @id,
    type: KeyTransform.call(@type.to_s, key_transform: @key_transform),
    attributes: KeyTransform.call(@attributes, key_transform: @key_transform)
  }

  if @relationships
    data[:relationships] = KeyTransform.call(
      @relationships.to_h,
      key_transform: @key_transform
    )
  end

  if shallow
    data
  else
    { data: data, meta: @meta }
  end
end

#to_json(_context = nil) ⇒ Object

Rails is awkward and calls #to_json with a context argument NOTE: Rails only method Hash#to_json



48
49
50
# File 'lib/jsonapi_helpers/serializers/data.rb', line 48

def to_json(_context = nil)
  to_h.to_json
end