Class: Ciri::RLP::Serializable::Schema

Inherits:
Object
  • Object
show all
Defined in:
lib/ciri/rlp/serializable.rb

Overview

Schema specific columns types of classes, normally you should not use Serializable::Schema directly

Defined Under Namespace

Classes: InvalidSchemaError

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(schema) ⇒ Schema

Returns a new instance of Schema.


85
86
87
88
89
90
91
92
93
94
95
96
97
98
# File 'lib/ciri/rlp/serializable.rb', line 85

def initialize(schema)
  keys = []
  @_schema = {}

  schema.each do |key|
    key, type = key.is_a?(Hash) ? key.to_a[0] : [key, nil]
    raise InvalidSchemaError.new("missing type #{type} for key #{key}") unless check_key_type(type)
    keys << key
    @_schema[key] = type
  end

  @_schema.freeze
  @keys = keys.freeze
end

Instance Attribute Details

#keysObject (readonly)

keys return data columns array


83
84
85
# File 'lib/ciri/rlp/serializable.rb', line 83

def keys
  @keys
end

Instance Method Details

#[](key) ⇒ Object

Get column type, see Serializable::TYPES for supported type


101
102
103
# File 'lib/ciri/rlp/serializable.rb', line 101

def [](key)
  @_schema[key]
end

#rlp_decode!(input, raw: true) ⇒ Object


120
121
122
123
124
125
126
127
# File 'lib/ciri/rlp/serializable.rb', line 120

def rlp_decode!(input, raw: true)
  data = raw ? RLP.decode(input) : input
  keys.each_with_index.map do |key, i|
    # decode data by type
    decoded_item = Serializable.decode_with_type(data[i], self[key])
    [key, decoded_item]
  end.to_h
end

#rlp_encode!(data, raw: true) ⇒ Object


112
113
114
115
116
117
118
# File 'lib/ciri/rlp/serializable.rb', line 112

def rlp_encode!(data, raw: true)
  # pre-encode, encode data to rlp compatible format(only string or array)
  data_list = keys.map do |key|
    Serializable.encode_with_type(data[key], self[key])
  end
  raw ? RLP.encode(data_list) : data_list
end

#validate!(data) ⇒ Object

Validate data, data is a Hash


106
107
108
109
110
# File 'lib/ciri/rlp/serializable.rb', line 106

def validate!(data)
  keys.each do |key|
    raise InvalidSchemaError.new("missing key #{key}") unless data.key?(key)
  end
end