alba 0.11.1 → 1.0.1

Sign up to get free protection for your applications and to get access to all the features.
@@ -1,75 +0,0 @@
1
- module Alba
2
- # This module represents how a resource should be serialized.
3
- module Serializer
4
- # @!parse include InstanceMethods
5
- # @!parse extend ClassMethods
6
-
7
- # @private
8
- def self.included(base)
9
- super
10
- base.class_eval do
11
- @_opts = {} unless instance_variable_defined?('@_opts')
12
- @_metadata = {} unless instance_variable_defined?('@_metadata')
13
- end
14
- base.include InstanceMethods
15
- base.extend ClassMethods
16
- end
17
-
18
- # Instance methods
19
- module InstanceMethods
20
- # @param resource [Alba::Resource]
21
- def initialize(resource)
22
- @resource = resource
23
- @hash = resource.serializable_hash
24
- @hash = {key.to_sym => @hash} if key
25
- # @hash is either Hash or Array
26
- @hash.is_a?(Hash) ? @hash.merge!(metadata.to_h) : @hash << metadata
27
- end
28
-
29
- # Use real encoder to actually serialize to JSON
30
- #
31
- # @return [String] JSON string
32
- def serialize
33
- Alba.encoder.call(@hash)
34
- end
35
-
36
- private
37
-
38
- def key
39
- opts = self.class._opts
40
- opts[:key] == true ? @resource.key : opts[:key]
41
- end
42
-
43
- def metadata
44
- metadata = self.class._metadata
45
- metadata.transform_values { |block| block.call(@resource.object) }
46
- end
47
- end
48
-
49
- # Class methods
50
- module ClassMethods
51
- attr_reader :_opts, :_metadata
52
-
53
- # @private
54
- def inherited(subclass)
55
- super
56
- %w[_opts _metadata].each { |name| subclass.instance_variable_set("@#{name}", public_send(name).clone) }
57
- end
58
-
59
- # Set options, currently key only
60
- #
61
- # @param key [Boolean, Symbol]
62
- def set(key: false)
63
- @_opts[:key] = key
64
- end
65
-
66
- # Set metadata
67
- #
68
- # @param name [String, Symbol] key for the metadata
69
- # @param block [Block] the content of the metadata
70
- def metadata(name, &block)
71
- @_metadata[name.to_sym] = block
72
- end
73
- end
74
- end
75
- end