Module: Barley::Serializable

Extended by:
ActiveSupport::Concern
Defined in:
lib/barley/serializable.rb

Overview

Makes a Model serializable

  • Allows setting a default model Serializer

Examples:

class Item < ApplicationRecord
  include Barley::Serializable

 # optionally define the default serializer, otherwise defaults to ItemSerializer
 serializer MyCustomItemSerializer, cache: true
end

#> Item.as_json

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.serializer(klass, cache: false) ⇒ Object

Examples:

without cache

serializer ItemSerializer

with cache

serializer ItemSerializer, cache: true

with cache and expires_in

serializer ItemSerializer, cache: {expires_in: 1.hour}

Parameters:

  • klass (Class)

    the serializer class

  • cache (Boolean, Hash<Symbol, ActiveSupport::Duration>) (defaults to: false)

    whether to cache the result, or a hash with options for the cache



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

Parameters:

  • options (Hash) (defaults to: nil)

    a customizable set of options

Options Hash (options):

  • :serializer (Class)

    the serializer to use

  • :cache (Boolean, Hash<Symbol, ActiveSupport::Duration>)

    whether to cache the result, or a hash with options for the cache

  • :root (Boolean)

    whether to include the root key

Returns:

  • (Hash)

    the serialized attributes



62
63
64
65
66
67
68
69
70
71
72
# File 'lib/barley/serializable.rb', line 62

def as_json(options = nil)
  options ||= {}
  serializer = options[:serializer] || self.serializer.class
  cache = options[:cache] || false
  root = options[:root] || false
  begin
    serializer.new(self, cache: cache, root: root).serializable_hash
  rescue NameError
    raise Barley::Error, "Could not find serializer for #{self}. Please define a #{serializer} class."
  end
end