Class: SimpleSerializer::Serializer

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

Class Attribute Summary collapse

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(object, _ = {}) ⇒ Serializer

Returns a new instance of Serializer.



57
58
59
# File 'lib/simple_serializer/serializer.rb', line 57

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

Class Attribute Details

._hash_attributesObject

Returns the value of attribute _hash_attributes.



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

def _hash_attributes
  @_hash_attributes
end

Instance Attribute Details

#objectObject

Returns the value of attribute object.



55
56
57
# File 'lib/simple_serializer/serializer.rb', line 55

def object
  @object
end

Class Method Details

.as_jsonObject



52
53
54
# File 'lib/simple_serializer/serializer.rb', line 52

def serialize(object)
  self.new(object).serialize
end

.hash_attributes(*attrs) ⇒ Object



34
35
36
37
38
39
40
41
42
# File 'lib/simple_serializer/serializer.rb', line 34

def hash_attributes(*attrs)
  @_hash_attributes.concat attrs

  attrs.each do |attr|
    define_method attr do
      object.send(attr)
    end unless method_defined?(attr)
  end
end

.inherited(base) ⇒ Object



30
31
32
# File 'lib/simple_serializer/serializer.rb', line 30

def inherited(base)
  base._hash_attributes = []
end

.serialize(object) ⇒ Object



48
49
50
# File 'lib/simple_serializer/serializer.rb', line 48

def serialize(object)
  self.new(object).serialize
end

.serialize_array(objects) ⇒ Object



44
45
46
# File 'lib/simple_serializer/serializer.rb', line 44

def serialize_array(objects)
  objects.map { |obj| serialize(obj) }
end

Instance Method Details

#extract_attributesObject



61
62
63
64
65
# File 'lib/simple_serializer/serializer.rb', line 61

def extract_attributes
  self.class._hash_attributes.dup.each_with_object({}) do |name, hash|
    hash[name] = send(name)
  end
end

#serialize(_ = {}) ⇒ Object Also known as: as_json



67
68
69
70
# File 'lib/simple_serializer/serializer.rb', line 67

def serialize(_={})
  return nil if object.nil?
  extract_attributes
end