class AbcJsonapi::Model

Attributes

model[R]
relationships[R]
resource_attributes[R]
resource_type[R]
virtual_attributes[R]

Public Class Methods

new(model:, resource_type:, resource_attributes:, virtual_attributes:, relationships:) click to toggle source
# File lib/abc_jsonapi/model.rb, line 8
def initialize(model:, resource_type:, resource_attributes:, virtual_attributes:, relationships:)
  @model = model
  @resource_type = resource_type.to_sym
  @resource_attributes = resource_attributes
  @virtual_attributes = virtual_attributes
  @relationships = relationships
end

Public Instance Methods

serializable_hash() click to toggle source
# File lib/abc_jsonapi/model.rb, line 16
def serializable_hash
  data = {}
  data[:id] = model.id.to_s
  data[:type] = resource_type
  data[:attributes] = transform_keys_if_necessary(attributes_hash)
  data[:relationships] = transform_keys_if_necessary(relationships_hash, true) if relationships.any?
  data
end

Private Instance Methods

attributes_hash() click to toggle source
# File lib/abc_jsonapi/model.rb, line 27
def attributes_hash
  result = {}
  resource_attributes.each do |attribute|
    result.merge!(attribute => model.public_send(attribute))
  end

  virtual_attributes.each do |attribute|
    attribute = AbcJsonapi::VirtualAttribute.new(
      model: model,
      name: attribute[:name],
      block: attribute[:block]
    )
    result.merge!(attribute.serializable_hash)
  end

  result
end
relationships_hash() click to toggle source
# File lib/abc_jsonapi/model.rb, line 45
def relationships_hash
  result = {}
  relationships.each do |relationship|
    rel_model = AbcJsonapi::Relationship.new(
      model: model,
      relationship: relationship[:name],
      type: relationship[:type],
      block: relationship[:block]
    )
    result[relationship[:name].to_sym] = rel_model.serializable_hash
  end
  result
end
transform_keys_if_necessary(hash, deep = false) click to toggle source
# File lib/abc_jsonapi/model.rb, line 59
def transform_keys_if_necessary(hash, deep = false)
  transform_method = deep ? 'deep_transform_keys' : 'transform_keys'

  if AbcJsonapi.config.transform_keys
    case AbcJsonapi.config.key_transform_method
    when 'camel'
      hash.public_send(transform_method){ |key| key.to_s.camelize(:lower).to_sym }
    when 'snake'
      hash.public_send(transform_method){ |key| key.to_s.underscore.to_sym }
    end
  end
end