-
Notifications
You must be signed in to change notification settings - Fork 1.4k
/
serializable_resource.rb
81 lines (66 loc) · 2.52 KB
/
serializable_resource.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
76
77
78
79
80
81
require 'set'
module ActiveModelSerializers
class SerializableResource
ADAPTER_OPTION_KEYS = Set.new([:include, :fields, :adapter, :meta, :meta_key, :links, :serialization_context, :key_transform])
include ActiveModelSerializers::Logging
delegate :serializable_hash, :as_json, :to_json, to: :adapter
notify :serializable_hash, :render
notify :as_json, :render
notify :to_json, :render
# Primary interface to composing a resource with a serializer and adapter.
# @return the serializable_resource, ready for #as_json/#to_json/#serializable_hash.
def initialize(resource, options = {})
@resource = resource
@adapter_opts, @serializer_opts =
options.partition { |k, _| ADAPTER_OPTION_KEYS.include? k }.map { |h| Hash[h] }
end
def serialization_scope=(scope)
serializer_opts[:scope] = scope
end
def serialization_scope
serializer_opts[:scope]
end
def serialization_scope_name=(scope_name)
serializer_opts[:scope_name] = scope_name
end
# NOTE: if no adapter is available, returns the resource itself. (i.e. adapter is a no-op)
def adapter
@adapter ||= find_adapter
end
alias adapter_instance adapter
def find_adapter
return resource unless serializer?
ActiveModelSerializers::Adapter.create(serializer_instance, adapter_opts)
rescue ActiveModel::Serializer::CollectionSerializer::NoSerializerError
resource
end
def serializer_instance
@serializer_instance ||= serializer.new(resource, serializer_opts)
end
# Get serializer either explicitly :serializer or implicitly from resource
# Remove :serializer key from serializer_opts
# Replace :serializer key with :each_serializer if present
def serializer
@serializer ||=
begin
@serializer = serializer_opts.delete(:serializer)
@serializer ||= ActiveModel::Serializer.serializer_for(resource)
if serializer_opts.key?(:each_serializer)
serializer_opts[:serializer] = serializer_opts.delete(:each_serializer)
end
@serializer
end
end
alias serializer_class serializer
# True when no explicit adapter given, or explicit appear is truthy (non-nil)
# False when explicit adapter is falsy (nil or false)
def use_adapter?
!(adapter_opts.key?(:adapter) && !adapter_opts[:adapter])
end
def serializer?
use_adapter? && !serializer.nil?
end
protected
attr_reader :resource, :adapter_opts, :serializer_opts
end
end