module RLP::Sedes::Serializable

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.

Attributes

_cached_rlp[RW]

Public Class Methods

included(base) click to toggle source
# File lib/rlp/sedes/serializable.rb, line 96
def included(base)
  base.extend ClassMethods
end
new(*args) click to toggle source
# File lib/rlp/sedes/serializable.rb, line 103
def initialize(*args)
  serializable_initialize parse_field_args(args)
end

Public Instance Methods

==(other) click to toggle source
# File lib/rlp/sedes/serializable.rb, line 155
def ==(other)
  return false unless other.class.respond_to?(:serialize)
  self.class.serialize(self) == other.class.serialize(other)
end
_set_field(field, value) click to toggle source
# File lib/rlp/sedes/serializable.rb, line 145
def _set_field(field, value)
  make_mutable! unless instance_variable_defined?(:@_mutable)

  if mutable? || !self.class.serializable_fields.has_key?(field)
    instance_variable_set :"@#{field}", value
  else
    raise ArgumentError, "Tried to mutate immutable object"
  end
end
make_immutable!() click to toggle source
# File lib/rlp/sedes/serializable.rb, line 164
def make_immutable!
  make_mutable!
  self.class.serializable_fields.keys.each do |field|
    ::RLP::Utils.make_immutable! send(field)
  end

  @_mutable = false
  self
end
make_mutable!() click to toggle source
# File lib/rlp/sedes/serializable.rb, line 174
def make_mutable!
  @_mutable = true
end
mutable?() click to toggle source
# File lib/rlp/sedes/serializable.rb, line 160
def mutable?
  @_mutable
end
parse_field_args(args) click to toggle source

Mimic python’s argument syntax, accept both normal arguments and named arguments. Normal argument overrides named argument.

# File lib/rlp/sedes/serializable.rb, line 111
def parse_field_args(args)
  h = {}

  options = args.last.is_a?(Hash) ? args.pop : {}
  field_set = self.class.serializable_fields.keys

  fields = self.class.serializable_fields.keys[0,args.size]
  fields.zip(args).each do |(field, arg)|
    h[field] = arg
    field_set.delete field
  end

  options.each do |field, value|
    if field_set.include?(field)
      h[field] = value
      field_set.delete field
    end
  end

  h
end
serializable_initialize(fields) click to toggle source
# File lib/rlp/sedes/serializable.rb, line 133
def serializable_initialize(fields)
  make_mutable!

  field_set = self.class.serializable_fields.keys
  fields.each do |field, value|
    _set_field field, value
    field_set.delete field
  end

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