Class: Veriform::Object

Inherits:
Object
  • Object
show all
Extended by:
Enumerable, Forwardable
Defined in:
lib/veriform/object.rb

Overview

Key/value pairs ala JSON objects or Protobuf messages

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initializeVeriform::Object

Create a new Veriform::Object



28
29
30
# File 'lib/veriform/object.rb', line 28

def initialize
  @fields = {}
end

Class Method Details

.from_tjson(obj) ⇒ Object

Create a Veriform::Object from a TJSON::Object

Raises:

  • (TypeError)


15
16
17
18
19
20
21
22
23
# File 'lib/veriform/object.rb', line 15

def self.from_tjson(obj)
  raise TypeError, "expected TJSON::Object, got #{obj.class}" unless obj.is_a?(TJSON::Object)

  new.tap do |result|
    obj.each do |key, value|
      result[Integer(key, 10)] = value.is_a?(TJSON::Object) ? from_tjson(value) : value
    end
  end
end

Instance Method Details

#[](key) ⇒ Object

Retrieve the value associated with a field identifier in a Veriform::Object

Parameters:

  • key (Integer)

    field identifier

Returns:

  • (Object)

    value associated with this key



37
38
39
# File 'lib/veriform/object.rb', line 37

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

#[]=(key, value) ⇒ Object

Sets the value associated with a field identifier

Parameters:

  • key (Integer)

    field identifier

  • value (Object)

    value associated with the given key

Returns:

  • (Object)

    newly set value

Raises:



50
51
52
53
54
55
56
# File 'lib/veriform/object.rb', line 50

def []=(key, value)
  raise TypeError, "key must be an integer: #{key.inspect}" unless key.is_a?(Integer)
  raise RangeError, "key must be positive: #{key.inspect}" if key < 0
  raise DuplicateFieldError, "duplicate field ID: #{key}" if @fields.key?(key)

  @fields[key] = value
end

#eql?(other) ⇒ Boolean Also known as: ==

Compare two Veriform::Objects by value for equality

Returns:

  • (Boolean)


73
74
75
76
77
78
79
80
81
82
# File 'lib/veriform/object.rb', line 73

def eql?(other)
  return false unless other.is_a?(self.class)
  return false unless keys.length == other.keys.length

  keys.each do |key|
    return false unless self[key].eql?(other[key])
  end

  true
end

#to_hHash

Return a hash representation of this object (and its children). This is akin to an ‘#as_json` method as seen in e.g. Rails.

Returns:

  • (Hash)

    a hash representation of this object



62
63
64
65
66
67
68
69
70
# File 'lib/veriform/object.rb', line 62

def to_h
  result = {}

  @fields.each do |k, v|
    result[k] = v.is_a?(self.class) ? v.to_h : v
  end

  result
end