Class: SimpleSerializer
- Inherits:
-
Object
- Object
- SimpleSerializer
- Defined in:
- lib/simple_serializer.rb
Constant Summary collapse
- VERSION =
'0.1.7'
Class Attribute Summary collapse
-
.fields ⇒ Object
readonly
Returns the value of attribute fields.
Class Method Summary collapse
- .[](object) ⇒ Object
- .attributes(*fields, **named, &block) ⇒ Object (also: attribute)
- .helpers ⇒ Object
- .inherited(sub) ⇒ Object
- .serialize(field, &block) ⇒ Object
- .to_h(object, opts = {}) ⇒ Object
- .to_json(object, opts = {}) ⇒ Object
Instance Method Summary collapse
-
#initialize(object, opts = {}) ⇒ SimpleSerializer
constructor
A new instance of SimpleSerializer.
- #to_h ⇒ Object
Constructor Details
#initialize(object, opts = {}) ⇒ SimpleSerializer
Returns a new instance of SimpleSerializer.
6 7 8 9 10 |
# File 'lib/simple_serializer.rb', line 6 def initialize(object, opts = {}) @include = opts[:include] || [] @exclude = opts[:exclude] || [] @object = object end |
Class Attribute Details
.fields ⇒ Object (readonly)
Returns the value of attribute fields.
19 20 21 |
# File 'lib/simple_serializer.rb', line 19 def fields @fields end |
Class Method Details
.[](object) ⇒ Object
39 40 41 |
# File 'lib/simple_serializer.rb', line 39 def [](object) to_h(object) end |
.attributes(*fields, **named, &block) ⇒ Object Also known as: attribute
51 52 53 54 55 56 57 |
# File 'lib/simple_serializer.rb', line 51 def attributes(*fields, **named, &block) @fields ||= {} fields.each { |k| @fields[k] = block } @fields.merge!(named) end |
.helpers ⇒ Object
25 26 27 28 29 30 31 32 33 34 35 36 37 |
# File 'lib/simple_serializer.rb', line 25 def helpers serializer = self Module.new.tap do |m| m.define_singleton_method(:included) do |base| base.define_method(:to_h) { |o = {}| serializer.to_h(self, o) } base.define_method(:to_json) { |o = {}| serializer.to_json(self, o) } base.define_method(:serializer_class) { serializer } end end end |
.inherited(sub) ⇒ Object
21 22 23 |
# File 'lib/simple_serializer.rb', line 21 def inherited(sub) sub.instance_variable_set(:@fields, fields.to_h.dup) end |
.serialize(field, &block) ⇒ Object
61 62 63 |
# File 'lib/simple_serializer.rb', line 61 def serialize(field, &block) attributes(field => Class.new(SimpleSerializer, &block)) end |
.to_h(object, opts = {}) ⇒ Object
43 44 45 |
# File 'lib/simple_serializer.rb', line 43 def to_h(object, opts = {}) new(object, opts).to_h end |
.to_json(object, opts = {}) ⇒ Object
47 48 49 |
# File 'lib/simple_serializer.rb', line 47 def to_json(object, opts = {}) to_h(object, opts).to_json end |
Instance Method Details
#to_h ⇒ Object
12 13 14 15 16 |
# File 'lib/simple_serializer.rb', line 12 def to_h return @object.map(&method(:to_h_single)) if @object.is_a?(Enumerable) to_h_single(@object) end |