Class: ActiveModel::ArraySerializer

Inherits:
Object
  • Object
show all
Extended by:
ActiveSupport::DescendantsTracker
Defined in:
lib/active_model/array_serializer.rb

Overview

Active Model Array Serializer

Serializes an Array, checking if each element implements the active_model_serializer method.

To disable serialization of root elements:

ActiveModel::ArraySerializer.root = false

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

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

Returns a new instance of ArraySerializer.



32
33
34
# File 'lib/active_model/array_serializer.rb', line 32

def initialize(object, options={})
  @object, @options = object, options
end

Instance Attribute Details

#objectObject (readonly)

Returns the value of attribute object.



18
19
20
# File 'lib/active_model/array_serializer.rb', line 18

def object
  @object
end

#optionsObject (readonly)

Returns the value of attribute options.



18
19
20
# File 'lib/active_model/array_serializer.rb', line 18

def options
  @options
end

Class Method Details

.cached(value = true) ⇒ Object

set perform caching like root



27
28
29
# File 'lib/active_model/array_serializer.rb', line 27

def cached(value = true)
  self.perform_caching = value
end

Instance Method Details

#as_json(*args) ⇒ Object



44
45
46
47
48
49
50
51
52
53
54
55
# File 'lib/active_model/array_serializer.rb', line 44

def as_json(*args)
  @options[:hash] = hash = {}
  @options[:unique_values] = {}

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

#include_meta(hash) ⇒ Object



40
41
42
# File 'lib/active_model/array_serializer.rb', line 40

def include_meta(hash)
  hash[meta_key] = @options[:meta] if @options.has_key?(:meta)
end

#meta_keyObject



36
37
38
# File 'lib/active_model/array_serializer.rb', line 36

def meta_key
  @options[:meta_key].try(:to_sym) || :meta
end

#serializable_arrayObject



67
68
69
70
71
72
73
74
75
# File 'lib/active_model/array_serializer.rb', line 67

def serializable_array
  if perform_caching?
    cache.fetch expand_cache_key([self.class.to_s.underscore, cache_key, 'serializable-array']) do
      _serializable_array
    end
  else
    _serializable_array
  end
end

#to_json(*args) ⇒ Object



57
58
59
60
61
62
63
64
65
# File 'lib/active_model/array_serializer.rb', line 57

def to_json(*args)
  if perform_caching?
    cache.fetch expand_cache_key([self.class.to_s.underscore, cache_key, 'to-json']) do
      super
    end
  else
    super
  end
end