Class: Arcgis::Connection

Inherits:
Object
  • Object
show all
Defined in:
lib/arcgis/connection.rb

Constant Summary collapse

@@object_registry =
{}

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(host:, username: nil, password: nil, token: nil) ⇒ Connection

Take in username/password upon initialization



9
10
11
12
13
14
15
16
17
# File 'lib/arcgis/connection.rb', line 9

def initialize(host:, username: nil, password: nil, token: nil)
  @host = host.sub(/\/$/,'')
  @token, @token_expires = token, nil
  @username, @password = username, password

  if username && password
    (username, password)
  end
end

Instance Attribute Details

#usernameObject (readonly)

Returns the value of attribute username.



4
5
6
# File 'lib/arcgis/connection.rb', line 4

def username
  @username
end

Instance Method Details

#default_paramsObject



55
56
57
# File 'lib/arcgis/connection.rb', line 55

def default_params
  @token.nil? ? {f: :json} : {f: :json, token: @token}
end

#handle_response(response) ⇒ Object



69
70
71
72
73
74
75
76
77
# File 'lib/arcgis/connection.rb', line 69

def handle_response(response)
  if response.success?
    r = JSON.parse(response.body)
    raise ErrorResponse.new(r["error"]) if r["error"]
    r
  else
    raise response.inspect
  end
end

#login(username, password) ⇒ Object



20
21
22
23
24
25
26
27
28
29
# File 'lib/arcgis/connection.rb', line 20

def (username, password)
  response = run(
    path: "/generateToken",
    method: "POST",
    body: {username: username, password: password, referer: "http://arcgis.com"}
  )

  @token = response["token"]
  @token_expires = Time.at(response["expires"]/1000)
end

#run(path:, method: "GET", params: {}, headers: {}, body: {}) ⇒ Object



40
41
42
43
44
45
46
47
48
49
50
51
52
# File 'lib/arcgis/connection.rb', line 40

def run(path:, method: "GET", params: {}, headers: {}, body: {})
  full_params = default_params.merge(params)

  # JSON encode array and hash fields
  params, body = sanitize_params(params), sanitize_params(body)

  request = Typhoeus::Request.new(
    @host + path,
    {method: method, params: full_params, headers: headers, body: body}
  )

  handle_response(request.run)
end

#sanitize_params(params) ⇒ Object

also used on body



61
62
63
64
65
66
# File 'lib/arcgis/connection.rb', line 61

def sanitize_params(params)
  params.reduce({}) do |agg,(k,v)|
    agg[k] = (v.is_a?(Hash) || v.is_a?(Array)) ? v.to_json : v
    agg
  end
end

#search(params = {}) ⇒ Object



32
33
34
35
36
37
# File 'lib/arcgis/connection.rb', line 32

def search(params={})
  run(
    path: "/search",
    params: params
  )
end