Module: RLP::Sedes::Serializable::ClassMethods

Includes:
Error
Defined in:
lib/rlp/sedes/serializable.rb

Instance Method Summary collapse

Instance Method Details

#deserialize(serial, exclude: nil, extra: {}) ⇒ Object


57
58
59
60
61
62
63
64
65
66
67
68
69
70
# File 'lib/rlp/sedes/serializable.rb', line 57

def deserialize(serial, exclude: nil, extra: {})
  begin
    values = serializable_sedes.deserialize(serial)
  rescue ListDeserializationError => e
    raise ObjectDeserializationError.new(serial: serial, sedes: self, list_exception: e)
  end

  params = Hash[*serializable_fields.keys.zip(values).flatten(1)]
  params.delete_if {|field, value| exclude.include?(field) } if exclude

  obj = self.new params.merge(extra)
  obj.instance_variable_set :@_mutable, false
  obj
end

#serializable_fieldsObject


35
36
37
# File 'lib/rlp/sedes/serializable.rb', line 35

def serializable_fields
  @serializable_fields
end

#serializable_sedesObject


39
40
41
# File 'lib/rlp/sedes/serializable.rb', line 39

def serializable_sedes
  @serializable_sedes ||= Sedes::List.new(elements: serializable_fields.values)
end

#serialize(obj) ⇒ Object


43
44
45
46
47
48
49
50
51
52
53
54
55
# File 'lib/rlp/sedes/serializable.rb', line 43

def serialize(obj)
  begin
    field_values = serializable_fields.keys.map {|k| obj.send k }
  rescue NoMethodError => e
    raise ObjectSerializationError.new(message: "Cannot serialize this object (missing attribute)", obj: obj)
  end

  begin
    serializable_sedes.serialize(field_values)
  rescue ListSerializationError => e
    raise ObjectSerializationError.new(obj: obj, sedes: self, list_exception: e)
  end
end

#set_serializable_fields(fields) ⇒ Object


17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
# File 'lib/rlp/sedes/serializable.rb', line 17

def set_serializable_fields(fields)
  raise "Cannot override serializable fields!" if @serializable_fields

  @serializable_fields = fields

  fields.keys.each do |field|
    class_eval <<-ATTR
      def #{field}
        @#{field}
      end

      def #{field}=(v)
        _set_field(:#{field}, v)
      end
    ATTR
  end
end