Module: FastSerializer::Serializer

Included in:
ArraySerializer
Defined in:
lib/fast_serializer/serializer.rb

Overview

Models can include this module to define themselves as serializers. A serializer is used to wrap an object and output a hash version of that object suitable for serialization to JSON or other formats.

To define what fields to serialize on the wrapped object, the serializer class must call the serialize class method:

This sample serializer will output an object as a hash with the keys :id and :name. The values for each field is gotten by calling the corresponding method on the serializer object. By default, each serialized field will automatically define a method that simply delegates to the wrapped object. So if you need provide special handling for a field or serialize a virtual field that doesn't exist on the parent object, you just need to implement the method on the serializer.

Serializers can implement their own options for controlling details about how to serialize the object.

All serializers will honor options for :include (include optional fields), :exclude (exclude fields).

Serializer can also be specified as cacheable. Cacheable serializer will store and fetch the serialized value from a cache. In order to user caching you must set the cache implementation. This can either be done on a global level (FastSerializer.cache) class level, or instance level (:cache option). Then you can specify serializers to be cacheable. This can be done on a class level with the cacheable directive or on an instance level with the :cacheable option. A time to live can also be set at the same levels using cache_ttl.

Serializers are designed to be reusable and must never have any internal state associated with them. Calling as_json on a serializer multiple times must always return the same value.

Serializing a nil object will result in nil rather than an empty hash.

Examples:

Defining a basic serializer

class PersonSerializer
  include FastSerializer::Serializer
  serialize :id, :name
end

Defining a virtual field

class PersonSerializer
  include FastSerializer::Serializer
  serialize :id, :name

  def name
    "#{object.first_name} #{object.last_name}"
  end
end

Defining a serializer with custom options

class PersonSerializer
  include FastSerializer::Serializer
  serialize :id, :name

  def name
    if option(:last_first)
      "#{object.last_name}, #{object.first_name}"
    else
      "#{object.first_name} #{object.last_name}"
    end
  end
end

serializer = PersonSerializer.new(person, :last_first => true)

Defined Under Namespace

Modules: ArrayHelper, ClassMethods

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Instance Attribute Details

#objectObject (readonly)

Return the wrapped object that is being serialized.



69
70
71
# File 'lib/fast_serializer/serializer.rb', line 69

def object
  @object
end

#optionsObject (readonly)

Return the options hash (if any) that specified optional details about how to serialize the object.



72
73
74
# File 'lib/fast_serializer/serializer.rb', line 72

def options
  @options
end

Class Method Details

.included(base) ⇒ Object



63
64
65
66
# File 'lib/fast_serializer/serializer.rb', line 63

def self.included(base)
  base.extend(ClassMethods)
  base.extend(ArrayHelper) unless base.is_a?(FastSerializer::ArraySerializer)
end

Instance Method Details

#==(other) ⇒ Object Also known as: eql?

:nodoc:



372
373
374
# File 'lib/fast_serializer/serializer.rb', line 372

def ==(other)
  other.instance_of?(self.class) && @object == other.object && @options == other.options
end

#as_json(*args) ⇒ Object Also known as: to_hash, to_h

Serialize the wrapped object into a format suitable for passing to a JSON parser.



321
322
323
324
325
# File 'lib/fast_serializer/serializer.rb', line 321

def as_json(*args)
  return nil unless object
  @_serialized ||= (cacheable? ? load_from_cache : load_hash).freeze
  @_serialized
end

#cacheObject

Return the cache implementation where this serializer can be stored.



354
355
356
# File 'lib/fast_serializer/serializer.rb', line 354

def cache
  @cache || self.class.cache
end

#cache_keyObject

Returns a array of the elements that make this serializer unique. The key is an array made up of the serializer class name, wrapped object, and serialization options hash.



366
367
368
369
# File 'lib/fast_serializer/serializer.rb', line 366

def cache_key
  object_cache_key = (object.respond_to?(:cache_key) ? object.cache_key : object)
  [self.class.name, object_cache_key, options_cache_key(options)]
end

#cache_ttlObject

Return the time to live in seconds this serializer can be cached for.



359
360
361
# File 'lib/fast_serializer/serializer.rb', line 359

def cache_ttl
  option(:cache_ttl) || self.class.cache_ttl
end

#cacheable?Boolean

Return true if this serializer is cacheable.

Returns:

  • (Boolean)


349
350
351
# File 'lib/fast_serializer/serializer.rb', line 349

def cacheable?
  option(:cacheable) || self.class.cacheable?
end

#initialize(object, options = nil) ⇒ Object

Create a new serializer for the specified object.

Options can be passed in to control how the object is serialized. Options supported by all Serializers:

  • :include - Field or array of optional field names that should be included in the serialized object.
  • :exclude - Field or array of field names that should be excluded from the serialized object.
  • :cacheable - Override the cacheable behavior set on the class.
  • :cache_ttl - Override the cache ttl set on the class.
  • :cache - Override the cache implementation set on the class.


310
311
312
313
314
315
316
317
318
# File 'lib/fast_serializer/serializer.rb', line 310

def initialize(object, options = nil)
  @object = object
  @options = options
  @cache = options[:cache] if options
  if @cache && defined?(ActiveSupport::Cache::Store) && @cache.is_a?(ActiveSupport::Cache::Store)
    @cache = Cache::ActiveSupportCache.new(@cache)
  end
  @_serialized = nil
end

#option(name) ⇒ Object

Fetch the specified option from the options hash.



340
341
342
# File 'lib/fast_serializer/serializer.rb', line 340

def option(name)
  @options[name] if @options
end

#scopeObject



344
345
346
# File 'lib/fast_serializer/serializer.rb', line 344

def scope
  option(:scope)
end

#to_json(options = {}) ⇒ Object

Convert the wrapped object to JSON format.



331
332
333
334
335
336
337
# File 'lib/fast_serializer/serializer.rb', line 331

def to_json(options = {})
  if defined?(MultiJson)
    MultiJson.dump(as_json, options)
  else
    JSON.dump(as_json)
  end
end