Module: RLP::Sedes::Serializable

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

Overview

Mixin for objects which can be serialized into RLP lists.

`fields` defines which attributes are serialized and how this is done. It is expected to be a hash in the form of `name => sedes`. Here, `name` is the name of an attribute and `sedes` is the sedes object that will be used to serialize the corresponding attribute. The object as a whole is then serialized as a list of those fields.

Defined Under Namespace

Modules: ClassMethods

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Instance Attribute Details

#_cached_rlpObject

Returns the value of attribute _cached_rlp


79
80
81
# File 'lib/rlp/sedes/serializable.rb', line 79

def _cached_rlp
  @_cached_rlp
end

Class Method Details

.included(base) ⇒ Object


74
75
76
# File 'lib/rlp/sedes/serializable.rb', line 74

def included(base)
  base.extend ClassMethods
end

Instance Method Details

#==(other) ⇒ Object


118
119
120
121
# File 'lib/rlp/sedes/serializable.rb', line 118

def ==(other)
  return false unless other.class.respond_to?(:serialize)
  self.class.serialize(self) == other.class.serialize(other)
end

#_set_field(field, value) ⇒ Object


106
107
108
109
110
111
112
113
114
115
116
# File 'lib/rlp/sedes/serializable.rb', line 106

def _set_field(field, value)
  unless instance_variable_defined?(:@_mutable)
    @_mutable = true
  end

  if mutable? || !self.class.serializable_fields.has_key?(field)
    instance_variable_set :"@#{field}", value
  else
    raise ArgumentError, "Tried to mutate immutable object"
  end
end

#initialize(*args) ⇒ Object


81
82
83
# File 'lib/rlp/sedes/serializable.rb', line 81

def initialize(*args)
  serializable_initialize(*args)
end

#make_immutable!Object


127
128
129
130
131
132
133
134
135
# File 'lib/rlp/sedes/serializable.rb', line 127

def make_immutable!
  @_mutable = true
  self.class.serializable_fields.keys.each do |field|
    ::RLP::Utils.make_immutable! send(field)
  end

  @_mutable = false
  self
end

#mutable?Boolean

Returns:

  • (Boolean)

123
124
125
# File 'lib/rlp/sedes/serializable.rb', line 123

def mutable?
  @_mutable
end

#serializable_initialize(*args) ⇒ Object

Raises:

  • (TypeError)

85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
# File 'lib/rlp/sedes/serializable.rb', line 85

def serializable_initialize(*args)
  options = args.last.is_a?(Hash) ? args.pop : {}

  field_set = self.class.serializable_fields.keys

  self.class.serializable_fields.keys.zip(args).each do |(field, arg)|
    break unless arg
    _set_field field, arg
    field_set.delete field
  end

  options.each do |field, value|
    if field_set.include?(field)
      _set_field field, value
      field_set.delete field
    end
  end

  raise TypeError, "Not all fields initialized" unless field_set.size == 0
end