Class: Seri::Serializer
- Inherits:
-
Object
- Object
- Seri::Serializer
- Defined in:
- lib/serializer.rb,
lib/serializer/value.rb,
lib/serializer/version.rb,
lib/serializer/value_fetcher.rb
Defined Under Namespace
Classes: Attribute, HashValue, SerializedValue, StaticValue, Value, ValueFetcher
Constant Summary collapse
- VERSION =
'2.0.12'.freeze
Instance Attribute Summary collapse
-
#object ⇒ Object
Returns the value of attribute object.
-
#scope ⇒ Object
Returns the value of attribute scope.
Class Method Summary collapse
- .attribute(key, condition: nil, from: nil, serializer: nil, **options) ⇒ Object
- .attributes ⇒ Object
Instance Method Summary collapse
-
#initialize(object, scope: {}) ⇒ Serializer
constructor
A new instance of Serializer.
-
#to_h ⇒ Object
Loops over all attributes and skips if a condition is defined and falsey.
- #to_json ⇒ Object
Constructor Details
#initialize(object, scope: {}) ⇒ Serializer
Returns a new instance of Serializer.
20 21 22 23 |
# File 'lib/serializer.rb', line 20 def initialize(object, scope: {}) @object = object @scope = scope end |
Instance Attribute Details
#object ⇒ Object
Returns the value of attribute object.
18 19 20 |
# File 'lib/serializer.rb', line 18 def object @object end |
#scope ⇒ Object
Returns the value of attribute scope.
18 19 20 |
# File 'lib/serializer.rb', line 18 def scope @scope end |
Class Method Details
.attribute(key, condition: nil, from: nil, serializer: nil, **options) ⇒ Object
14 15 16 |
# File 'lib/serializer.rb', line 14 def self.attribute(key, condition: nil, from: nil, serializer: nil, **) attributes.push(Attribute.new(key, condition, from, serializer, )) end |
.attributes ⇒ Object
10 11 12 |
# File 'lib/serializer.rb', line 10 def self.attributes @attributes ||= [] end |
Instance Method Details
#to_h ⇒ Object
Loops over all attributes and skips if a condition is defined and falsey
26 27 28 29 30 31 32 |
# File 'lib/serializer.rb', line 26 def to_h self.class.attributes.each_with_object({}) do |attribute, obj| next if attribute.condition && !public_send(attribute.condition) obj[attribute.key] = ValueFetcher.fetch(attribute, object, self) end end |
#to_json ⇒ Object
34 35 36 |
# File 'lib/serializer.rb', line 34 def to_json(*) Oj.dump(to_h, mode: :json) end |