Class: Spotify::SDK::Model

Inherits:
OpenStruct
  • Object
show all
Defined in:
lib/spotify/sdk/model.rb

Overview

For each SDK response object (i.e. Device), we have a Model class. We’re using OpenStruct.

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(payload, parent) ⇒ Model

Initialize a new Model instance.

Examples:

module Spotify
  class SDK
    class User < Model
    end
  end
end

@base = Spotify::SDK::Base.new(@sdk)
@user = Spotify::SDK::User.new({ username: "hi" }, @base)
@user.username # => "hi"

Parameters:

  • payload (Hash)

    The response payload.

  • parent (Spotify::SDK)

    The SDK object for context.



27
28
29
30
31
32
33
34
35
# File 'lib/spotify/sdk/model.rb', line 27

def initialize(payload, parent)
  @payload = payload
  raise "Expected payload to be of Hash type" unless @payload.instance_of?(Hash)

  @parent = parent
  raise "Expected parent to be of Spotify::SDK::Base type" unless @parent.is_a?(Spotify::SDK::Base)

  super(payload)
end

Instance Attribute Details

#parentObject (readonly)

A reference to Spotify::SDK::Connect.



48
49
50
# File 'lib/spotify/sdk/model.rb', line 48

def parent
  @parent
end

Class Method Details

.alias_attribute(new_method, attribute) ⇒ Object

:nodoc:



51
52
53
54
55
56
57
58
59
# File 'lib/spotify/sdk/model.rb', line 51

def alias_attribute(new_method, attribute) # :nodoc:
  if attribute.is_a?(Symbol)
    define_method(new_method) { send(attribute) }
  else
    define_method(new_method) do
      self.class.hash_selector(to_h, attribute)
    end
  end
end

.hash_selector(hash, selector) ⇒ Object



61
62
63
64
65
66
# File 'lib/spotify/sdk/model.rb', line 61

def hash_selector(hash, selector)
  hash.deep_symbolize_keys!
  segments = selector.split(".")
  hash = hash[segments.shift.try(:to_sym)] while segments.any?
  hash
end

Instance Method Details

#to_hObject

:nodoc:



37
38
39
# File 'lib/spotify/sdk/model.rb', line 37

def to_h # :nodoc:
  super.to_h.except(:parent)
end

#to_json(*_args) ⇒ Object

:nodoc:



41
42
43
# File 'lib/spotify/sdk/model.rb', line 41

def to_json(*_args) # :nodoc:
  to_h.to_json
end