Module: Barley::Serializable
- Extended by:
- ActiveSupport::Concern
- Defined in:
- lib/barley/serializable.rb
Overview
Makes a Model serializable
-
Allows setting a default model Serializer
Class Method Summary collapse
Instance Method Summary collapse
-
#as_json(options = nil) ⇒ Hash
Serializes the model.
Class Method Details
.serializer(klass, cache: false) ⇒ Object
32 33 34 35 36 37 38 39 40 41 42 |
# File 'lib/barley/serializable.rb', line 32 def serializer(klass, cache: false) # We need to silence the warnings because we are defining a method with the same name as the parameter # This avoids : # - warning: method redefined; discarding old serializer # - warning: previous definition of serializer was here Kernel.silence_warnings do define_method(:serializer) do klass.new(self, cache: cache) end end end |
Instance Method Details
#as_json(options = nil) ⇒ Hash
Note:
this method does not provide default rails options like ‘only` or `except`. This is because the Barley serializer should be the only place where the attributes are defined.
Serializes the model
62 63 64 65 66 67 68 69 70 71 72 73 |
# File 'lib/barley/serializable.rb', line 62 def as_json( = nil) ||= {} serializer = [:serializer] || self.serializer.class cache = [:cache] || false root = [:root] || false begin serializer.new(self, cache: cache, root: root).serializable_hash .as_json(only: [:only], except: [:except]) rescue NameError raise Barley::Error, "Could not find serializer for #{self}. Please define a #{serializer} class." end end |