Class: Veriform::Object
- Inherits:
-
Object
- Object
- Veriform::Object
- Extended by:
- Enumerable, Forwardable
- Defined in:
- lib/veriform/object.rb
Overview
Key/value pairs ala JSON objects or Protobuf messages
Class Method Summary collapse
-
.from_tjson(obj) ⇒ Object
Create a Veriform::Object from a TJSON::Object.
Instance Method Summary collapse
-
#[](key) ⇒ Object
Retrieve the value associated with a field identifier in a Veriform::Object.
-
#[]=(key, value) ⇒ Object
Sets the value associated with a field identifier.
-
#eql?(other) ⇒ Boolean
(also: #==)
Compare two Veriform::Objects by value for equality.
-
#initialize ⇒ Veriform::Object
constructor
Create a new Veriform::Object.
-
#to_h ⇒ Hash
Return a hash representation of this object (and its children).
Constructor Details
#initialize ⇒ Veriform::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
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
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
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
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_h ⇒ Hash
Return a hash representation of this object (and its children). This is akin to an ‘#as_json` method as seen in e.g. Rails.
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 |