Class: Apiarist::Serializer
- Inherits:
-
SimpleDelegator
- Object
- SimpleDelegator
- Apiarist::Serializer
- Includes:
- Serialization
- Defined in:
- lib/apiarist/serializer.rb
Instance Attribute Summary collapse
-
#context ⇒ Object
readonly
Returns the value of attribute context.
Class Method Summary collapse
- .association(name, opts = {}) ⇒ Object
- .associations(*associations) ⇒ Object
- .attribute(name, opts = {}) ⇒ Object
- .attributes(*names) ⇒ Object
- .scope(name, &block) ⇒ Object
Instance Method Summary collapse
- #as_json(_ = {}) ⇒ Object
-
#initialize(resource, context = self, opts = {}) ⇒ Serializer
constructor
A new instance of Serializer.
- #serialization_context ⇒ Object
Methods included from Serialization
Constructor Details
#initialize(resource, context = self, opts = {}) ⇒ Serializer
Returns a new instance of Serializer.
10 11 12 13 14 |
# File 'lib/apiarist/serializer.rb', line 10 def initialize(resource, context = self, opts = {}) @resource = resource, @context = context @options = opts super(resource) end |
Instance Attribute Details
#context ⇒ Object (readonly)
Returns the value of attribute context.
8 9 10 |
# File 'lib/apiarist/serializer.rb', line 8 def context @context end |
Class Method Details
.association(name, opts = {}) ⇒ Object
54 55 56 |
# File 'lib/apiarist/serializer.rb', line 54 def association(name, opts = {}) attribute(name, opts.merge(type: :association)) end |
.associations(*associations) ⇒ Object
58 59 60 61 |
# File 'lib/apiarist/serializer.rb', line 58 def associations(*associations) opts = associations. associations.each { |name| association(name, opts) } end |
.attribute(name, opts = {}) ⇒ Object
44 45 46 47 |
# File 'lib/apiarist/serializer.rb', line 44 def attribute(name, opts = {}) self._keys = _keys.dup _keys[name] = opts end |
.attributes(*names) ⇒ Object
49 50 51 52 |
# File 'lib/apiarist/serializer.rb', line 49 def attributes(*names) opts = names. names.each { |name| attribute(name, opts) } end |
.scope(name, &block) ⇒ Object
63 64 65 66 67 |
# File 'lib/apiarist/serializer.rb', line 63 def scope(name, &block) (if: name) do |scope| scope.instance_eval(&block) end end |
Instance Method Details
#as_json(_ = {}) ⇒ Object
18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 |
# File 'lib/apiarist/serializer.rb', line 18 def as_json(_ = {}) json = {} _keys.each_with_object(json) do |(name, opts), hash| serialization_opts = opts.dup key = serialization_opts.delete(:as) || name if serialization_scope_include?(serialization_opts.delete(:if)) case serialization_opts.delete(:type) when :association value = serialize(send(name), serialization_opts) else value = send(name) end hash[key] = value end end json end |
#serialization_context ⇒ Object
39 40 41 |
# File 'lib/apiarist/serializer.rb', line 39 def serialization_context context.serialization_context end |