Module: OpenCalais::Connection

Included in:
Client
Defined in:
lib/open_calais/connection.rb

Defined Under Namespace

Classes: HashieWrapper

Constant Summary collapse

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

Instance Method Summary collapse

Instance Method Details

#connection(options = {}) ⇒ Object



43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
# File 'lib/open_calais/connection.rb', line 43

def connection(options={})
  opts = merge_default_options(options)
  FaradayMiddleware::Mashify.mash_class = HashieWrapper
  Faraday::Connection.new(opts) do |connection|
    connection.request  :url_encoded
    connection.response :mashify
    connection.response :logger if ENV['DEBUG']
    connection.response :raise_error

    if opts[:headers][OpenCalais::HEADERS[:output_format]] == OpenCalais::OUTPUT_FORMATS[:json]
      connection.response :json, :content_type => /\bjson$/
    else
      connection.response :xml
    end

    connection.adapter(adapter)
  end

end

#merge_default_options(opts = {}) ⇒ Object



21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
# File 'lib/open_calais/connection.rb', line 21

def merge_default_options(opts={})
  headers = opts.delete(:headers) || {}
  options = {
    :headers => {
      # generic http headers
      'User-Agent'   => user_agent,
      'Accept'       => "#{OpenCalais::OUTPUT_FORMATS[:json]};charset=utf-8",

      # open calais default headers
      OpenCalais::HEADERS[:license_id]    => api_key,
      OpenCalais::HEADERS[:content_type]  => OpenCalais::CONTENT_TYPES[:raw],
      OpenCalais::HEADERS[:output_format] => OpenCalais::OUTPUT_FORMATS[:json],
      OpenCalais::HEADERS[:language]      => 'English'
    },
    :ssl => {:verify => false},
    :url => endpoint
  }.merge(opts)
  options[:headers] = options[:headers].merge(headers)
  OpenCalais::HEADERS.each{|k,v| options[:headers][v] = options.delete(k) if options.key?(k)}
  options.select{|k,v| ALLOWED_OPTIONS.include?(k.to_sym)}
end