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:

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

This sample serializer will output an object as a hash with keys :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.

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

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

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

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)

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.

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.



66
67
68
# File 'lib/fast_serializer/serializer.rb', line 66

def object
  @object
end

#optionsObject (readonly)

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



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

def options
  @options
end

Class Method Details

.included(base) ⇒ Object



60
61
62
63
# File 'lib/fast_serializer/serializer.rb', line 60

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:



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

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.



317
318
319
320
321
# File 'lib/fast_serializer/serializer.rb', line 317

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.



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

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.



362
363
364
365
# File 'lib/fast_serializer/serializer.rb', line 362

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.



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

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

#cacheable?Boolean

Return true if this serializer is cacheable.

Returns:

  • (Boolean)


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

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.



306
307
308
309
310
311
312
313
314
# File 'lib/fast_serializer/serializer.rb', line 306

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.



336
337
338
# File 'lib/fast_serializer/serializer.rb', line 336

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

#scopeObject



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

def scope
  option(:scope)
end

#to_json(options = {}) ⇒ Object

Convert the wrapped object to JSON format.



327
328
329
330
331
332
333
# File 'lib/fast_serializer/serializer.rb', line 327

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