Class: Spotify::Struct

Inherits:
FFI::Struct
  • Object
show all
Extended by:
TypeSafety
Defined in:
lib/spotify/structs.rb

Overview

Spotify::Struct is a regular FFI::Struct, but with type checking that happens in the Spotify::API namespace, and it also allows you to initialize structs with a hash.

Class Method Summary collapse

Instance Method Summary collapse

Methods included from TypeSafety

to_native, type_class

Constructor Details

#initialize(pointer = nil, *layout, &block) ⇒ Struct

When initialized with a hash, assigns each value of the hash to the newly created struct before returning.

If not given a hash, it behaves exactly as FFI::Struct.

Parameters:

  • pointer (#each_pair, FFI::Pointer, nil) (defaults to: nil)
  • layout (Array<Symbol, Type>)


24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
# File 'lib/spotify/structs.rb', line 24

def initialize(pointer = nil, *layout, &block)
  if pointer.respond_to?(:each_pair)
    options = pointer
    pointer = nil
  else
    options = {}
  end

  super(pointer, *layout, &block)

  if defined?(self.class::DEFAULTS)
    options = self.class::DEFAULTS.merge(options)
  end

  options.each_pair do |key, value|
    self[key] = value
  end
end

Class Method Details

.enclosing_moduleSpotify::API

This is used by FFI to do type lookups when creating the struct layout. By overriding this we can trick FFI into looking up types in the right location.

Returns:



13
14
15
# File 'lib/spotify/structs.rb', line 13

def self.enclosing_module
  Spotify::API
end

Instance Method Details

#to_hHash

Convert the struct to a hash.

Returns:

  • (Hash)


46
47
48
# File 'lib/spotify/structs.rb', line 46

def to_h
  Hash[members.zip(values)]
end

#to_sString

String representation of the struct. Looks like a Hash.

Returns:

  • (String)


53
54
55
# File 'lib/spotify/structs.rb', line 53

def to_s
  "<#{self.class.name} #{to_h}>"
end