class JSONAPIHelpers::Serializers::Data

Public Class Methods

new( id:, type:, attributes: {}, meta: {}, relationships: nil, key_transform: JSONAPIHelpers.config.key_transform ) click to toggle source
# 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

Public Instance Methods

to_h(shallow: false) click to toggle source
# 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) click to toggle source

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

# File lib/jsonapi_helpers/serializers/data.rb, line 48
def to_json(_context = nil)
  to_h.to_json
end