Module: JSONAPI::Serializable::Resource::KeyFormat

Defined in:
lib/jsonapi/serializable/resource/key_format.rb

Overview

Extension for handling automatic key formatting of

attributes/relationships.

Examples:

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`.

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.extended(klass) ⇒ Object



26
27
28
29
30
31
32
# 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) ⇒ Object



17
18
19
20
21
22
23
24
# 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

Instance Method Details

#attribute(name, options = {}, &block) ⇒ Object

Handles automatic key formatting for attributes.



53
54
55
56
# 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

#inherited(klass) ⇒ Object



34
35
36
37
# 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) ⇒ Object

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

via a block.

Examples:

key_format -> (key) { key.capitalize }
key_format { |key| key.capitalize }


48
49
50
# 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) ⇒ Object Also known as: has_many, has_one, belongs_to

Handles automatic key formatting for relationships.



59
60
61
62
63
64
65
# 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