Class: CapsuleCRM::Serializer

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

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(options = {}) ⇒ Serializer

Returns a new instance of Serializer.



5
6
7
# File 'lib/capsule_crm/serializer.rb', line 5

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

Instance Attribute Details

#objectObject (readonly)

Returns the value of attribute object.



3
4
5
# File 'lib/capsule_crm/serializer.rb', line 3

def object
  @object
end

#optionsObject (readonly)

Returns the value of attribute options.



3
4
5
# File 'lib/capsule_crm/serializer.rb', line 3

def options
  @options
end

Class Method Details

.serialize_collection(klass, collection) ⇒ Object



19
20
21
22
23
24
25
26
# File 'lib/capsule_crm/serializer.rb', line 19

def self.serialize_collection(klass, collection)
  collection = collection.map do |item|
    options = klass.serializable_options.dup
    options.include_root = false
    ::CapsuleCRM::Serializer.new(options).serialize(item)
  end
  { klass.serializable_options.root => collection }
end

Instance Method Details

#collection_rootObject



41
42
43
# File 'lib/capsule_crm/serializer.rb', line 41

def collection_root
  @collection_root ||= options.collection_root || root.pluralize
end

#rootObject



36
37
38
39
# File 'lib/capsule_crm/serializer.rb', line 36

def root
  @root ||= options.root ||
    object.class.to_s.demodulize.downcase.singularize.camelize(:lower)
end

#serialize(object) ⇒ Object



9
10
11
12
13
14
15
16
17
# File 'lib/capsule_crm/serializer.rb', line 9

def serialize(object)
  @object = object
  @serialized ||=
    if include_root?
      serialize_with_root
    else
      serialize_without_root
    end
end

#serialize_with_rootObject



28
29
30
# File 'lib/capsule_crm/serializer.rb', line 28

def serialize_with_root
  { root => build_attributes_hash }.stringify_keys
end

#serialize_without_rootObject



32
33
34
# File 'lib/capsule_crm/serializer.rb', line 32

def serialize_without_root
  build_attributes_hash
end