Class: BaseCradle::ApiObject

Inherits:
Object
  • Object
show all
Defined in:
lib/basecradle/api_object.rb

Overview

A read-only, wire-exact view of one API JSON object.

Subclasses declare their wire fields with the attribute macro; readers return the wire value untouched (names mirror the API’s JSON exactly). Two deliberate behaviors:

  • A field the API added after this SDK release is still readable via [] (the API is additive-only — the SDK never hides what the platform says).

  • A declared field the API did not return raises MissingFieldError (with an explanation) rather than returning nil — a silent nil could mean “hidden from you” or “actually null”, and the SDK never guesses which.

Objects built by a client carry a reference to it, so resource verbs added in later releases (e.g. timeline.lock) can act on the platform.

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(data, client: nil) ⇒ ApiObject

Returns a new instance of ApiObject.



30
31
32
33
# File 'lib/basecradle/api_object.rb', line 30

def initialize(data, client: nil)
  @data = data
  @client = client
end

Class Method Details

.attribute(name, wrap: nil) ⇒ Object

Declare a wire field. wrap: names a model class to wrap the value in (a Hash becomes that model; an Array of Hashes becomes an Array of that model).



37
38
39
40
41
42
43
44
# File 'lib/basecradle/api_object.rb', line 37

def self.attribute(name, wrap: nil)
  key = name.to_s
  define_method(name) do
    raise_missing(key) unless @data.key?(key)
    value = @data[key]
    wrap ? wrap_value(value, wrap) : value
  end
end

Instance Method Details

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



57
58
59
# File 'lib/basecradle/api_object.rb', line 57

def ==(other)
  other.instance_of?(self.class) && other.to_h == @data
end

#[](key) ⇒ Object

Raw wire access — returns whatever the API sent for key (or nil if absent), without wrapping. The escape hatch for fields newer than this SDK release.



48
49
50
# File 'lib/basecradle/api_object.rb', line 48

def [](key)
  @data[key.to_s]
end

#hashObject



62
63
64
# File 'lib/basecradle/api_object.rb', line 62

def hash
  [ self.class, @data ].hash
end

#inspectObject



66
67
68
# File 'lib/basecradle/api_object.rb', line 66

def inspect
  "#<#{self.class} #{@data.keys.sort.join(', ')}>"
end

#to_hObject

The underlying wire data (a Hash). Read-only by convention.



53
54
55
# File 'lib/basecradle/api_object.rb', line 53

def to_h
  @data
end