module JSONAPI::Serializable::Resource::KeyFormat

Extension for handling automatic key formatting of

attributes/relationships.

@example

class SerializableUser < JSONAPI::Serializable::Resource
  extend JSONAPI::Serializable::Resource::KeyFormat
  key_format -> (key) { key.camelize }

  attribute :user_name
  has_many :close_friends
end
# => will modify the serialized keys to `UserName` and `CloseFriends`.

Attributes

_key_formatter[RW]

Public Class Methods

extended(klass) click to toggle source
# File lib/jsonapi/serializable/resource/key_format.rb, line 26
def self.extended(klass)
  klass.class_eval do
    class << self
      attr_accessor :_key_formatter
    end
  end
end
prepended(klass) click to toggle source
# File lib/jsonapi/serializable/resource/key_format.rb, line 17
        def self.prepended(klass)
          warn <<-EOT
  DERPRECATION WARNING (called from #{caller_locations(1...2).first}):
  Prepending `#{name}' is deprecated and will be removed in future releases. Use `Object#extend' instead.
  EOT

          klass.extend self
        end

Public Instance Methods

attribute(name, options = {}, &block) click to toggle source

Handles automatic key formatting for attributes.

Calls superclass method
# File lib/jsonapi/serializable/resource/key_format.rb, line 53
def attribute(name, options = {}, &block)
  block ||= proc { @object.public_send(name) }
  super(_key_formatter.call(name), options, &block)
end
belongs_to(name, options = {}, &block)
Alias for: relationship
has_many(name, options = {}, &block)

NOTE(beauby): Re-aliasing those is necessary for the

overridden `#relationship` method to be called.
Alias for: relationship
has_one(name, options = {}, &block)
Alias for: relationship
inherited(klass) click to toggle source
Calls superclass method
# File lib/jsonapi/serializable/resource/key_format.rb, line 34
def inherited(klass)
  super
  klass._key_formatter = _key_formatter
end
key_format(callable = nil, &block) click to toggle source

Set the callable responsible for formatting keys, either directly, or

via a block.

@example

key_format -> (key) { key.capitalize }

@example

key_format { |key| key.capitalize }
# File lib/jsonapi/serializable/resource/key_format.rb, line 48
def key_format(callable = nil, &block)
  self._key_formatter = callable || block
end
relationship(name, options = {}, &block) click to toggle source

Handles automatic key formatting for relationships.

Calls superclass method
# File lib/jsonapi/serializable/resource/key_format.rb, line 59
def relationship(name, options = {}, &block)
  rel_block = proc do
    data { @object.public_send(name) }
    instance_eval(&block) unless block.nil?
  end
  super(_key_formatter.call(name), options, &rel_block)
end
Also aliased as: has_many, has_one, belongs_to