Class: Prototok::Serializers::Base

Inherits:
Object
  • Object
show all
Defined in:
lib/prototok/serializers.rb

Direct Known Subclasses

Time, Token

Constant Summary collapse

KEY_OPERATIONS =
%i[nil empty].freeze

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(object) ⇒ Base

Returns a new instance of Base.



10
11
12
# File 'lib/prototok/serializers.rb', line 10

def initialize(object)
  @object = object
end

Instance Attribute Details

#objectObject (readonly)

Returns the value of attribute object.



8
9
10
# File 'lib/prototok/serializers.rb', line 8

def object
  @object
end

Class Method Details

.apply_key_ops!(result) ⇒ Object



81
82
83
84
85
86
87
88
89
# File 'lib/prototok/serializers.rb', line 81

def apply_key_ops!(result)
  key_ops.each do |key, ops|
    ops.each do |check, op|
      val = result[key]
      apply_op(result, key, op) if check_value val, check
    end
  end
  result
end

.apply_op(result, key, op) ⇒ Object



73
74
75
76
77
78
79
# File 'lib/prototok/serializers.rb', line 73

def apply_op(result, key, op)
  if op.is_a? Symbol
    result.send op, key
  else
    op.call(result, key)
  end
end

.attribute(*names, **options) ⇒ Object Also known as: attributes



40
41
42
43
44
45
46
47
# File 'lib/prototok/serializers.rb', line 40

def attribute(*names, **options)
  names.uniq!
  update_key_ops(*names, **options)
  names.each do |name|
    attribute_storage[name] = Attribute.new(options)
    define_attribute_method name
  end
end

.attribute_storageObject



65
66
67
# File 'lib/prototok/serializers.rb', line 65

def attribute_storage
  @attribute_storage ||= {}
end

.check_value(val, check) ⇒ Object



91
92
93
94
95
96
97
98
# File 'lib/prototok/serializers.rb', line 91

def check_value(val, check)
  if check.is_a?(Symbol)
    check_method = "#{check}?"
    val.respond_to?(check_method) && val.send(check_method)
  else
    check.call(val)
  end
end

.decode(data) ⇒ Object



49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
# File 'lib/prototok/serializers.rb', line 49

def decode(data)
  apply_key_ops!(data)
  result = attribute_storage.map do |name, attribute|
    serializer = attribute.serializer
    key = pick_key data, name
    next unless key
    value = data[key]
    if serializer
      [name, serializer.decode(value)]
    else
      [name, value]
    end
  end.compact
  Hash[result]
end

.key_opsObject



69
70
71
# File 'lib/prototok/serializers.rb', line 69

def key_ops
  @key_ops ||= {}
end

Instance Method Details

#encodeObject



16
17
18
19
20
21
22
# File 'lib/prototok/serializers.rb', line 16

def encode
  if attribute_storage.empty?
    @object.respond_to?(:to_h) ? @object.to_h : @object
  else
    Hash[map_attributes]
  end
end