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

ARRAYS =
%w[
  Array
  ActiveRecord_AssociationRelation
  ActiveRecord_Associations_CollectionProxy
].freeze
VERSION =
'1.0.0'.freeze

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

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

Returns a new instance of Serializer.



25
26
27
28
# File 'lib/serializer.rb', line 25

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

Instance Attribute Details

#objectObject

Returns the value of attribute object.



23
24
25
# File 'lib/serializer.rb', line 23

def object
  @object
end

#scopeObject

Returns the value of attribute scope.



23
24
25
# File 'lib/serializer.rb', line 23

def scope
  @scope
end

Class Method Details

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



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

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

.attributesObject



15
16
17
# File 'lib/serializer.rb', line 15

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

Instance Method Details

#to_hObject

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



31
32
33
34
35
36
37
# File 'lib/serializer.rb', line 31

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

    obj[attribute.key] = serialize_value(attribute)
  end
end

#to_jsonObject



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

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