Class: Answers::Client

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

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(config = {}) ⇒ Client

Returns a new instance of Client.



48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
# File 'lib/answers/client.rb', line 48

def initialize(config = {})
  # use the default
  url = Protocol::BASE_PATH
  
  # or use the provided url, if one is provided
  if config[:url]
    url = config[:url]
  end
  
  # put it in a hash
  faraday_defaults = {
    url: url 
  }
  
  @connection = Faraday.new(faraday_defaults) do |faraday|
    #faraday.response :logger                  # log requests to STDOUT
    faraday.adapter  Faraday.default_adapter  # make requests with Net::HTTP
    faraday.headers['Content-Type'] = Protocol::DEFAULT_CONTENT_TYPE
    faraday.headers[Protocol::EMAIL_HEADER_KEY] = config[:user_email] if config[:user_email]
    faraday.headers[Protocol::TOKEN_HEADER_KEY] = config[:user_token] if config[:user_token]
  end
end

Instance Attribute Details

#connectionObject (readonly)

Returns the value of attribute connection.



46
47
48
# File 'lib/answers/client.rb', line 46

def connection
  @connection
end

Instance Method Details

#delete(path) ⇒ Object



98
99
100
# File 'lib/answers/client.rb', line 98

def delete(path)
  request(:delete, path)
end

#get(path, params = nil) ⇒ Object



80
81
82
83
84
# File 'lib/answers/client.rb', line 80

def get(path, params=nil)
  request(:get, path) do |req|
    req.params = params if params
  end
end

#handle_response(response) ⇒ Object



102
103
104
105
106
107
# File 'lib/answers/client.rb', line 102

def handle_response(response)
  if response.status == 401
    raise Answers::Error.new "401 Unauthorized"
  end
    JSON.parse(response.body)
end

#post(path, body = nil) ⇒ Object



86
87
88
89
90
# File 'lib/answers/client.rb', line 86

def post(path, body=nil)
  request(:post, path) do |req|
    req.body = body.to_json if body
  end
end

#put(path, body = nil) ⇒ Object



92
93
94
95
96
# File 'lib/answers/client.rb', line 92

def put(path, body=nil)
  request(:put, path) do |req|
    req.body = body.to_json if body
  end
end

#request(method, path, &block) ⇒ Object



71
72
73
74
75
76
77
78
# File 'lib/answers/client.rb', line 71

def request(method, path, &block)
  response = @connection.send(method) do |req|
    req.url(path)
    block.call(req) if block_given?
  end
  
  handle_response(response)
end