Class: Nested::Serializer
- Inherits:
-
Object
- Object
- Nested::Serializer
- Defined in:
- lib/nested/serializer.rb
Instance Attribute Summary collapse
-
#excludes ⇒ Object
Returns the value of attribute excludes.
-
#includes ⇒ Object
Returns the value of attribute includes.
Instance Method Summary collapse
- #+(field) ⇒ Object
- #-(field) ⇒ Object
-
#initialize(includes = []) ⇒ Serializer
constructor
A new instance of Serializer.
- #serialize ⇒ Object
Constructor Details
#initialize(includes = []) ⇒ Serializer
Returns a new instance of Serializer.
5 6 7 8 |
# File 'lib/nested/serializer.rb', line 5 def initialize(includes=[]) @includes = includes.clone @excludes = [] end |
Instance Attribute Details
#excludes ⇒ Object
Returns the value of attribute excludes.
3 4 5 |
# File 'lib/nested/serializer.rb', line 3 def excludes @excludes end |
#includes ⇒ Object
Returns the value of attribute includes.
3 4 5 |
# File 'lib/nested/serializer.rb', line 3 def includes @includes end |
Instance Method Details
#+(field) ⇒ Object
10 11 12 13 14 15 16 |
# File 'lib/nested/serializer.rb', line 10 def +(field) field = field.is_a?(SerializerField) ? field : SerializerField.new(field, ->{ true }) @includes << field unless @includes.detect{|e| e.name == field.name} @excludes = @excludes.reject{|e| e.name == field.name} self end |
#-(field) ⇒ Object
18 19 20 21 22 23 |
# File 'lib/nested/serializer.rb', line 18 def -(field) field = field.is_a?(SerializerField) ? field : SerializerField.new(field, ->{ true }) @excludes << field unless @excludes.detect{|e| e.name == field.name} self end |
#serialize ⇒ Object
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 |
# File 'lib/nested/serializer.rb', line 25 def serialize this = self ->(obj) do obj = ::HashWithIndifferentAccess.new(obj) if obj.is_a?(Hash) excludes = this.excludes.select{|e| instance_exec(&e.condition)} if obj this.includes.reject{|e| excludes.detect{|e2| e2.name == e.name}}.inject({}) do |memo, field| if instance_exec(&field.condition) case field.name when Symbol memo[field.name] = obj.is_a?(Hash) ? obj[field.name] : obj.send(field.name) when Hash field_name, proc = field.name.to_a.first memo[field_name] = instance_exec(obj, &proc) end end memo end else nil end end end |