Class: Bech32::Nostr::TLVEntry

Inherits:
Object
  • Object
show all
Defined in:
lib/bech32/nostr/entity.rb,
sig/bech32/nostr/entity.rbs

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(type, value, label = nil) ⇒ TLVEntry

Initialize TLV entry.

Parameters:

  • type (Integer)
  • value (String, Integer)
  • label (String, nil) (defaults to: nil)


20
21
22
23
24
25
26
# File 'sig/bech32/nostr/entity.rbs', line 20

def initialize(type, value, label = nil)
  raise ArgumentError, "Type #{type} unsupported." unless TLVEntity::TYPES.include?(type)

  @type = type
  @value = value
  @label = label
end

Instance Attribute Details

#labelString? (readonly)

Returns the value of attribute label.

Returns:

  • (String, nil)


27
28
29
# File 'lib/bech32/nostr/entity.rb', line 27

def label
  @label
end

#typeInteger (readonly)

Returns the value of attribute type.

Returns:

  • (Integer)


26
27
28
# File 'lib/bech32/nostr/entity.rb', line 26

def type
  @type
end

#valueString, Integer (readonly)

Returns the value of attribute value.

Returns:

  • (String, Integer)


28
29
30
# File 'lib/bech32/nostr/entity.rb', line 28

def value
  @value
end

Instance Method Details

#hex_string?(str) ⇒ Boolean

Check if string is hex encoded.

Parameters:

  • str (String)

Returns:

  • (Boolean)


71
72
73
74
75
76
# File 'lib/bech32/nostr/entity.rb', line 71

def hex_string?(str)
  return false if str.bytes.any? { |b| b > 127 }
  return false if str.length % 2 != 0
  hex_chars = str.chars.to_a
  hex_chars.all? { |c| c =~ /[0-9a-fA-F]/ }
end

#to_payloadString

Convert to binary payload.

Returns:

  • (String)


40
41
42
43
44
45
46
47
48
# File 'lib/bech32/nostr/entity.rb', line 40

def to_payload
  data = if value.is_a?(Integer)
           [value].pack('N')
         else
           hex_string?(value) ? [value].pack('H*') : value
         end
  len = data.bytesize
  [type, len].pack('CC') + data
end

#to_sString

String representation.

Returns:

  • (String)


26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
# File 'sig/bech32/nostr/entity.rbs', line 26

def to_s
  type_label = case type
               when TLVEntity::TYPE_SPECIAL
                 'special'
               when TLVEntity::TYPE_RELAY
                 'relay'
               when TLVEntity::TYPE_AUTHOR
                 'author'
               when TLVEntity::TYPE_KIND
                 'kind'
               else
                 'unknown'
               end
  "#{type_label}: #{value}"
end