Module: ScopedSerializer

Defined in:
lib/scoped_serializer.rb,
lib/scoped_serializer/scope.rb,
lib/scoped_serializer/version.rb,
lib/scoped_serializer/serializer.rb,
lib/scoped_serializer/base_serializer.rb,
lib/scoped_serializer/array_serializer.rb,
lib/scoped_serializer/default_serializer.rb,
lib/scoped_serializer/collection_serializer.rb

Overview

ScopedSerializer takes care of complex and abstract serialization classes. It does this by allowing serialization scopes. For example, you can define a collection and a resource scope. This means you can render a different JSON output based on context (index/show). You can define any scope you want, there are no predefined scopes.

ScopedSerializer supports association and automatically eager loads them when needed.

ScopedSerializer.render(@order, :resource)
ScopedSerializer.render(Order.order('id ASC'), :collection)

Examples:


class OrderSerializer < ScopedSerializer::Serializer
  attributes :status, :price_in_cents

  scope :collection do
    association :customer => :addresses
  end

  scope :resource do
    association :customer
    association :notes, :employee
  end
end

Defined Under Namespace

Classes: ArraySerializer, BaseSerializer, CollectionSerializer, DefaultSerializer, Scope, Serializer

Constant Summary collapse

VERSION =
"0.1.0"

Class Method Summary collapse

Class Method Details

.find_serializer(object) ⇒ Object

Finds serializer based on object’s class.



69
70
71
72
73
74
75
76
77
78
79
80
# File 'lib/scoped_serializer.rb', line 69

def find_serializer(object)
  return object.serializer_class if object.respond_to?(:serializer_class)

  case object
  when ActiveRecord::Relation, ActiveRecord::Associations::CollectionProxy
    CollectionSerializer
  when Array
    ArraySerializer
  else
    find_serializer_by_class(object.class)
  end
end

.find_serializer_by_class(object_class) ⇒ Object



82
83
84
# File 'lib/scoped_serializer.rb', line 82

def find_serializer_by_class(object_class)
  "#{object_class.name}Serializer".safe_constantize
end

.for(object, scope = :default, options = {}) ⇒ Object

Returns an instantized serializer for the given object.



56
57
58
59
60
61
62
63
64
# File 'lib/scoped_serializer.rb', line 56

def for(object, scope=:default, options={})
  if object.respond_to?(:each)
    serializer = find_serializer(object)
  else
    serializer = options[:serializer] || find_serializer(object) || DefaultSerializer
  end

  serializer.new(object, scope, options) if serializer
end

.render(object, scope = :default, options = {}) ⇒ Hash

Renders a given object. Object can be an ActiveRecord object, array or a ActiveRecord collection.

Returns:

  • (Hash)


45
46
47
48
49
50
51
# File 'lib/scoped_serializer.rb', line 45

def render(object, scope=:default, options={})
  options.merge!({
    :super => true
  })

  self.for(object, scope, options).as_json
end