Class: Coderbits::Client

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

Constant Summary collapse

BASE_URL =

default faraday options

"https://coderbits.com/"
HEADERS =
{ accept: 'application/json' }
SSL =
{ verify: false }

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(options = {}) ⇒ Client

create instance of faraday



12
13
14
15
16
17
18
19
20
21
22
# File 'lib/coderbits/client.rb', line 12

def initialize options = {}
  options = safe(options, [:headers, :ssl])

  params = {
    url: BASE_URL,
    headers: options[:headers] || HEADERS.merge({'User-Agent' => "Ruby Coderbits #{Coderbits::VERSION}"}),
    ssl: options[:ssl] || SSL
  }

  @connection = Faraday.new params
end

Instance Attribute Details

#connectionObject (readonly)

faraday instance only for reading



9
10
11
# File 'lib/coderbits/client.rb', line 9

def connection
  @connection
end

Instance Method Details

#get(username, options = {}) ⇒ Object

gets user data



25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
# File 'lib/coderbits/client.rb', line 25

def get username, options = {}
  begin
    response = @connection.get "/#{username}.json", safe(options, [:account, :callback])

    status = response.status
    error  = false
  rescue Exception => e
    status = -1
    error  = "Connection error: #{e}"
  end

  # return string if options has callback
  return response.body if options[:callback]

  # parse json
  user_data = MultiJson.load response.body, symbolize_keys: true

  # set error if loaded json is empty
  error = "User not found" if user_data.empty?

  # set status and error message to returned data
  user_data[:status] = status
  user_data[:error]  = error

  # hashie
  Coderbits::Object.new user_data
end