Class: Balanced::Client

Inherits:
Object
  • Object
show all
Defined in:
lib/balanced/client.rb

Constant Summary collapse

DEFAULTS =
{
  :scheme => 'http',
  :host => 'localhost',
  :port => 5000,
  :version => '1',
  :logging_level => 'WARN',
  :connection_timeout => 30,
  :read_timeout => 30,
  :logger => nil,
  :ssl_verify => true
}

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(api_key, options = {}) ⇒ Client

Returns a new instance of Client.



26
27
28
29
30
# File 'lib/balanced/client.rb', line 26

def initialize(api_key, options={})
  @api_key = api_key.nil? ? api_key : api_key.strip
  @config = DEFAULTS.merge options
  build_conn
end

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

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



77
78
79
80
81
82
83
84
# File 'lib/balanced/client.rb', line 77

def method_missing(method, *args, &block)
  if is_http_method? method
    conn.basic_auth(api_key, '') unless api_key.nil?
    conn.send method, *args
  else
    super method, *args, &block
  end
end

Instance Attribute Details

#api_keyObject

Returns the value of attribute api_key.



24
25
26
# File 'lib/balanced/client.rb', line 24

def api_key
  @api_key
end

#configObject

Returns the value of attribute config.



24
25
26
# File 'lib/balanced/client.rb', line 24

def config
  @config
end

#connObject (readonly)

Returns the value of attribute conn.



23
24
25
# File 'lib/balanced/client.rb', line 23

def conn
  @conn
end

Instance Method Details

#build_connObject



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
# File 'lib/balanced/client.rb', line 32

def build_conn
  if config[:logger]
    logger = config[:logger]
  else
    logger = Logger.new(STDOUT)
    logger.level = Logger.const_get(config[:logging_level].to_s)
  end

  Faraday.register_middleware :response,
      :handle_balanced_errors => lambda {Faraday::Response::RaiseBalancedError}

  options = {
    :request => {
      :open_timeout => config[:connection_timeout],
      :timeout => config[:read_timeout]
    },
    :ssl => {
      :verify => @config[:ssl_verify] # Only set this to false for testing
    }
  }
  @conn = Faraday.new(url, options) do |cxn|
    cxn.request  :json

    cxn.response :logger, logger
    cxn.response :handle_balanced_errors
    cxn.response :json
    # cxn.response :raise_error  # raise exceptions on 40x, 50x responses
    cxn.adapter  Faraday.default_adapter
  end
  conn.path_prefix = '/'
  conn.headers['User-Agent'] = "balanced-ruby/#{Balanced::VERSION}"
end

#urlObject

end



69
70
71
72
73
74
75
# File 'lib/balanced/client.rb', line 69

def url
  builder = (config[:scheme] == 'http') ? URI::HTTP : URI::HTTPS

  builder.build ({:host => config[:host],
                     :port => config[:port],
                     :scheme => config[:scheme]})
end