Module: BrightSerializer::Serializer
- Includes:
- Extensions
- Defined in:
- lib/bright_serializer/serializer.rb
Defined Under Namespace
Modules: ClassMethods
Constant Summary
collapse
- SUPPORTED_TRANSFORMATION =
%i[camel camel_lower dash underscore].freeze
- DEFAULT_OJ_OPTIONS =
{ mode: :compat, time_format: :ruby, use_to_json: true }.freeze
Class Method Summary
collapse
Instance Method Summary
collapse
Methods included from Extensions
instrumentation_extension
Class Method Details
.included(base) ⇒ Object
17
18
19
20
21
|
# File 'lib/bright_serializer/serializer.rb', line 17
def self.included(base)
super
base.extend ClassMethods
base.instance_variable_set(:@attributes_to_serialize, [])
end
|
Instance Method Details
#initialize(object, **options) ⇒ Object
23
24
25
26
27
|
# File 'lib/bright_serializer/serializer.rb', line 23
def initialize(object, **options)
@object = object
@params = options.delete(:params)
@fields = options.delete(:fields)
end
|
#serializable_hash ⇒ Object
Also known as:
to_hash
39
40
41
42
43
44
45
|
# File 'lib/bright_serializer/serializer.rb', line 39
def serializable_hash
if @object.respond_to?(:each) && !@object.respond_to?(:each_pair)
@object.map { |o| serialize(o, instance_attributes_to_serialize) }
else
serialize(@object, instance_attributes_to_serialize)
end
end
|
#serializable_json(*_args) ⇒ Object
Also known as:
to_json
49
50
51
|
# File 'lib/bright_serializer/serializer.rb', line 49
def serializable_json(*_args)
::Oj.dump(to_hash, DEFAULT_OJ_OPTIONS)
end
|
#serialize(object, attributes_to_serialize) ⇒ Object
29
30
31
32
33
34
35
36
37
|
# File 'lib/bright_serializer/serializer.rb', line 29
def serialize(object, attributes_to_serialize)
return if object.nil?
attributes_to_serialize.each_with_object({}) do |attribute, result|
next unless attribute.condition?(object, @params)
result[attribute.transformed_key] = attribute.serialize(self, object, @params)
end
end
|