-
Notifications
You must be signed in to change notification settings - Fork 35
/
key_format.rb
75 lines (68 loc) · 2.28 KB
/
key_format.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
module JSONAPI
module Serializable
class Resource
# 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`.
module KeyFormat
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
def self.extended(klass)
klass.class_eval do
class << self
attr_accessor :_key_formatter
end
end
end
def inherited(klass)
super
klass._key_formatter = _key_formatter
end
# 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 }
#
def key_format(callable = nil, &block)
self._key_formatter = callable || block
end
# Handles automatic key formatting for attributes.
def attribute(name, options = {}, &block)
block ||= proc { @object.public_send(name) }
super(_key_formatter.call(name), options, &block)
end
# Handles automatic key formatting for relationships.
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
# NOTE(beauby): Re-aliasing those is necessary for the
# overridden `#relationship` method to be called.
alias has_many relationship
alias has_one relationship
alias belongs_to relationship
end
end
end
end