Class: ActiveModel::ArraySerializer

Inherits:
Object
  • Object
show all
Defined in:
lib/active_model/serializer.rb

Overview

Active Model Array Serializer

It serializes an array checking if each element that implements the active_model_serializer method passing down the current scope.

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(object, scope, options = {}) ⇒ ArraySerializer

Returns a new instance of ArraySerializer.



12
13
14
15
# File 'lib/active_model/serializer.rb', line 12

def initialize(object, scope, options={})
  @object, @scope, @options = object, scope, options
  @hash = options[:hash]
end

Instance Attribute Details

#objectObject (readonly)

Returns the value of attribute object.



10
11
12
# File 'lib/active_model/serializer.rb', line 10

def object
  @object
end

#scopeObject (readonly)

Returns the value of attribute scope.



10
11
12
# File 'lib/active_model/serializer.rb', line 10

def scope
  @scope
end

Instance Method Details

#as_json(*args) ⇒ Object



27
28
29
30
31
32
33
34
35
36
# File 'lib/active_model/serializer.rb', line 27

def as_json(*args)
  @hash = {}
  array = serializable_array.as_json(*args)

  if root = @options[:root]
    @hash.merge!(root => array)
  else
    array
  end
end

#serializable_arrayObject



17
18
19
20
21
22
23
24
25
# File 'lib/active_model/serializer.rb', line 17

def serializable_array
  @object.map do |item|
    if item.respond_to?(:active_model_serializer) && (serializer = item.active_model_serializer)
      serializer.new(item, scope, :hash => @hash)
    else
      item
    end
  end
end