Module: TopTL::Model

Included in:
GlobalStats, Listing, StatsResult, VoteCheck, Voter, WebhookConfig, WebhookTestResult
Defined in:
lib/toptl/types.rb

Overview

Mixin providing a ‘from_hash` factory that silently ignores unknown response keys so the SDK doesn’t break when the API adds new fields.

Subclasses declare their fields via ‘field :name` (with an optional default) and an `.from_hash` class method that pulls each field off a raw response hash. The full response is always preserved on `raw`.

Defined Under Namespace

Modules: ClassMethods

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Instance Attribute Details

#rawObject (readonly)

Returns the value of attribute raw.



15
16
17
# File 'lib/toptl/types.rb', line 15

def raw
  @raw
end

Class Method Details

.included(base) ⇒ Object



11
12
13
# File 'lib/toptl/types.rb', line 11

def self.included(base)
  base.extend(ClassMethods)
end

Instance Method Details

#initialize(attrs = {}) ⇒ Object



34
35
36
37
38
39
40
41
# File 'lib/toptl/types.rb', line 34

def initialize(attrs = {})
  self.class.fields.each do |name|
    value = attrs.key?(name) ? attrs[name] : self.class.defaults[name]
    value = value.call if value.is_a?(Proc)
    instance_variable_set(:"@#{name}", value)
  end
  @raw = attrs[:raw] || {}
end

#to_hObject



43
44
45
46
47
48
# File 'lib/toptl/types.rb', line 43

def to_h
  out = {}
  self.class.fields.each { |n| out[n] = instance_variable_get(:"@#{n}") }
  out[:raw] = @raw
  out
end