Class: Speechmatics::Response

Inherits:
Object
  • Object
show all
Defined in:
lib/speechmatics/response.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(response, request = {}) ⇒ Response

Returns a new instance of Response.



7
8
9
10
11
12
# File 'lib/speechmatics/response.rb', line 7

def initialize(response, request={})
  @raw     = response
  @request = request

  check_for_error(response)
end

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

#method_missing(method_name, *args, &block) ⇒ Object

Coerce any method calls for body attributes



56
57
58
59
60
61
62
63
64
65
66
# File 'lib/speechmatics/response.rb', line 56

def method_missing(method_name, *args, &block)
  if self.has_key?(method_name.to_s)
    self.[](method_name, &block)
  elsif self.body.respond_to?(method_name)
    self.body.send(method_name, *args, &block)
  elsif self.request[:api].respond_to?(method_name)
    self.request[:api].send(method_name, *args, &block)
  else
    super
  end
end

Instance Attribute Details

#rawObject

Returns the value of attribute raw.



5
6
7
# File 'lib/speechmatics/response.rb', line 5

def raw
  @raw
end

#requestObject

Returns the value of attribute request.



5
6
7
# File 'lib/speechmatics/response.rb', line 5

def request
  @request
end

Instance Method Details

#[](key) ⇒ Object



42
43
44
45
46
47
48
# File 'lib/speechmatics/response.rb', line 42

def [](key)
  if self.object.is_a?(Array) || self.object.is_a?(Hash)
    self.object[key]
  else
    self.object.send(:"#{key}")
  end
end

#bodyObject



26
27
28
# File 'lib/speechmatics/response.rb', line 26

def body
  self.raw.body
end

#check_for_error(response) ⇒ Object



14
15
16
17
18
19
20
21
22
23
24
# File 'lib/speechmatics/response.rb', line 14

def check_for_error(response)
  status_code_type = response.status.to_s[0]
  case status_code_type
  when "2"
    # puts "all is well, status: #{response.status}"
  when "4", "5"
    raise "Whoops, error back from Speechmatics: #{response.status}"
  else
    raise "Unrecongized status code: #{response.status}"
  end
end

#has_key?(key) ⇒ Boolean

Returns:

  • (Boolean)


50
51
52
# File 'lib/speechmatics/response.rb', line 50

def has_key?(key)
  self.object.is_a?(Hash) && self.object.has_key?(key)
end

#objectObject



34
35
36
# File 'lib/speechmatics/response.rb', line 34

def object
  body[object_name].nil? ? body : body[object_name]
end

#object_nameObject



30
31
32
# File 'lib/speechmatics/response.rb', line 30

def object_name
  self.request[:api].class.name.split("::").last.underscore
end

#objectsObject



38
39
40
# File 'lib/speechmatics/response.rb', line 38

def objects
  Array(self.object)
end