Class: SimpleSerializer
- Inherits:
-
Object
- Object
- SimpleSerializer
- Defined in:
- lib/simple_serializer.rb
Constant Summary collapse
- VERSION =
'0.1.4'
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) ⇒ Object
- .to_json(object) ⇒ Object
Instance Method Summary collapse
-
#initialize(object) ⇒ SimpleSerializer
constructor
A new instance of SimpleSerializer.
- #to_h ⇒ Object
Constructor Details
#initialize(object) ⇒ SimpleSerializer
Returns a new instance of SimpleSerializer.
6 7 8 |
# File 'lib/simple_serializer.rb', line 6 def initialize(object) @object = object end |
Class Attribute Details
.fields ⇒ Object (readonly)
Returns the value of attribute fields.
17 18 19 |
# File 'lib/simple_serializer.rb', line 17 def fields @fields end |
Class Method Details
.[](object) ⇒ Object
37 38 39 |
# File 'lib/simple_serializer.rb', line 37 def [](object) to_h(object) end |
.attributes(*fields, **named, &block) ⇒ Object Also known as: attribute
49 50 51 52 53 54 55 |
# File 'lib/simple_serializer.rb', line 49 def attributes(*fields, **named, &block) @fields ||= {} fields.each { |k| @fields[k] = block } @fields.merge!(named) end |
.helpers ⇒ Object
23 24 25 26 27 28 29 30 31 32 33 34 35 |
# File 'lib/simple_serializer.rb', line 23 def helpers serializer = self Module.new.tap do |m| m.define_singleton_method(:included) do |base| base.define_method(:to_h) { serializer.to_h(self) } base.define_method(:to_json) { serializer.to_json(self) } base.define_method(:serializer_class) { serializer } end end end |
.inherited(sub) ⇒ Object
19 20 21 |
# File 'lib/simple_serializer.rb', line 19 def inherited(sub) sub.instance_variable_set(:@fields, fields.to_h.dup) end |
.serialize(field, &block) ⇒ Object
59 60 61 |
# File 'lib/simple_serializer.rb', line 59 def serialize(field, &block) attributes(field => Class.new(SimpleSerializer, &block)) end |
.to_h(object) ⇒ Object
41 42 43 |
# File 'lib/simple_serializer.rb', line 41 def to_h(object) new(object).to_h end |
.to_json(object) ⇒ Object
45 46 47 |
# File 'lib/simple_serializer.rb', line 45 def to_json(object) to_h(object).to_json end |
Instance Method Details
#to_h ⇒ Object
10 11 12 13 14 |
# File 'lib/simple_serializer.rb', line 10 def to_h return @object.map(&method(:to_h_single)) if @object.is_a?(Enumerable) to_h_single(@object) end |