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.



37
38
39
40
# File 'lib/basecradle/api_object.rb', line 37

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).



44
45
46
47
48
49
50
51
# File 'lib/basecradle/api_object.rb', line 44

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?



64
65
66
# File 'lib/basecradle/api_object.rb', line 64

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.



55
56
57
# File 'lib/basecradle/api_object.rb', line 55

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

#hashObject



69
70
71
# File 'lib/basecradle/api_object.rb', line 69

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

#inspectObject



73
74
75
# File 'lib/basecradle/api_object.rb', line 73

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

#to_hObject

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



60
61
62
# File 'lib/basecradle/api_object.rb', line 60

def to_h
  @data
end