Class: Serializer

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

Defined Under Namespace

Classes: Attribute, SerializerError

Constant Summary collapse

VERSION =
"0.1.0"

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(object, scope: {}) ⇒ Serializer

Returns a new instance of Serializer.



19
20
21
22
# File 'lib/serializer.rb', line 19

def initialize(object, scope: {})
  @object = object
  @scope = scope
end

Instance Attribute Details

#objectObject

Returns the value of attribute object.



17
18
19
# File 'lib/serializer.rb', line 17

def object
  @object
end

#scopeObject

Returns the value of attribute scope.



17
18
19
# File 'lib/serializer.rb', line 17

def scope
  @scope
end

Class Method Details

.attribute(key, condition: nil, from: nil, serializer: nil, **options) ⇒ Object



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

def self.attribute(key, condition: nil, from: nil, serializer: nil, **options)
  attributes.push(Attribute.new(key, condition, from, serializer, options))
end

.attributesObject



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

def self.attributes
  @attributes ||= []
end

Instance Method Details

#to_hObject

Loops over all attributes and skips if a condition is defined and falsey



25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
# File 'lib/serializer.rb', line 25

def to_h
  self.class.attributes.each_with_object({}) do |attribute, obj|
    next if attribute.condition && !public_send(attribute.condition)

    extraction_key = attribute.from || attribute.key

    # Fetches a value from an attribute by checking if there's a ..
    # .. static value set, or a ..
    # .. method defined in the serializer, or a ..
    # .. method/attribute defined in the object or ..
    # .. it raises an error
    value = if attribute.options.has_key?(:static_value)
              attribute.options.fetch(:static_value)
            elsif respond_to?(extraction_key)
              public_send(extraction_key)
            elsif object.respond_to?(extraction_key) && attribute.serializer
              value = object.public_send(extraction_key)

              serialize_value(value, attribute.serializer)
            elsif object.respond_to?(extraction_key)
              object.public_send(extraction_key)
            else
              raise SerializerError, "unknown attribute '#{extraction_key}'"
            end

    obj[attribute.key] = value
  end
end

#to_jsonObject



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

def to_json(*)
  Appsignal.instrument('json.serialize', 'Serializer', self.class.to_s) do
    Oj.dump(to_h, mode: :json)
  end
end