Module: Speechmatics::Connection

Included in:
API
Defined in:
lib/speechmatics/connection.rb

Constant Summary collapse

ALLOWED_OPTIONS =
[
  :headers,
  :url,
  :params,
  :request,
  :ssl
].freeze

Instance Method Summary collapse

Instance Method Details

#connection(options = {}) ⇒ Object



32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
# File 'lib/speechmatics/connection.rb', line 32

def connection(options={})
  if options[:allow_text]
    allow_text = true
    options.delete(:allow_text)
  else
    allow_text =false
  end
  opts = merge_default_options(options)

  @conn ||= Faraday::Connection.new(opts) do |connection|

    if Faraday::VERSION =~ /^0\.7\.(.*)/
      connection.use Faraday::Request::Multipart
      connection.use Faraday::Request::UrlEncoded

      connection.use FaradayMiddleware::Mashify
      connection.use Faraday::Response::Logger if ENV['DEBUG']
      connection.use FaradayMiddleware::ParseJson

      connection.use "Faraday::Adapter::#{adapter.to_s.classify}".constantize
    else
      connection.request  :multipart
      connection.request  :url_encoded

      connection.response :mashify
      connection.response :logger if ENV['DEBUG']
      if allow_text
        connection.response :json, :content_type => /\bjson$/
      else
        connection.response :json
      end
      connection.adapter(*adapter)
    end
  end
end

#merge_default_options(opts = {}) ⇒ Object



16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
# File 'lib/speechmatics/connection.rb', line 16

def merge_default_options(opts={})
  opts = opts.slice(*ALLOWED_OPTIONS)
  headers = opts.delete(:headers) || {}
  params = opts.delete(:params) || {}
  options = {
    url: endpoint,
    params: { auth_token: auth_token },
    headers: { 'User-Agent' => user_agent, 'Accept' => 'application/json' },
    ssl: { verify: false },
    request: { timeout: 120 }
  }.merge(opts)
  options[:headers] = options[:headers].merge(headers)
  options[:params] = options[:params].merge(params)
  options
end