Class: BinaryCodec::Issue

Inherits:
SerializedType show all
Defined in:
lib/binary-codec/types/issue.rb

Instance Attribute Summary

Attributes inherited from SerializedType

#bytes

Class Method Summary collapse

Instance Method Summary collapse

Methods inherited from SerializedType

from_bytes, from_hex, from_json, get_type_by_name, #to_byte_sink, #to_bytes, #to_hex, #value_of

Constructor Details

#initialize(bytes = nil) ⇒ Issue

Returns a new instance of Issue.



5
6
7
# File 'lib/binary-codec/types/issue.rb', line 5

def initialize(bytes = nil)
  super(bytes || [])
end

Class Method Details

.from(value) ⇒ Object

Raises:

  • (StandardError)


9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
# File 'lib/binary-codec/types/issue.rb', line 9

def self.from(value)
  return value if value.is_a?(Issue)

  if value.is_a?(String)
    return Issue.new(hex_to_bytes(value))
  end

  if value.is_a?(Hash) || value.is_a?(::Hash)
    bytes = []
    bytes.concat(Currency.from(value['currency']).to_bytes)
    bytes.concat(AccountId.from(value['issuer']).to_bytes) if value['issuer']
    return Issue.new(bytes)
  end

  raise StandardError, "Cannot construct Issue from #{value.class}"
end

.from_parser(parser, size_hint = nil) ⇒ Object



26
27
28
29
30
31
32
33
34
# File 'lib/binary-codec/types/issue.rb', line 26

def self.from_parser(parser, size_hint = nil)
  bytes = []
  return Issue.new(bytes) if parser.end?
  bytes.concat(parser.read(20)) # Currency
  unless parser.end? || (size_hint && size_hint <= 20)
    bytes.concat(parser.read(20))
  end
  Issue.new(bytes)
end

Instance Method Details

#to_json(_definitions = nil, _field_name = nil) ⇒ Object



36
37
38
39
40
41
42
43
44
45
# File 'lib/binary-codec/types/issue.rb', line 36

def to_json(_definitions = nil, _field_name = nil)
  parser = BinaryParser.new(to_hex)
  result = {}
  result['currency'] = Currency.from_parser(parser).to_json
  result['issuer'] = AccountId.from_parser(parser).to_json unless parser.end?
  result
rescue
  # Fallback for partial/invalid binary
  { 'currency' => Currency.new(to_bytes[0, 20]).to_json }
end