Class: HaveAPI::Client::Communicator

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

Instance Method Summary collapse

Constructor Details

#initialize(url) ⇒ Communicator

Returns a new instance of Communicator.



10
11
12
13
14
# File 'lib/haveapi/client/communicator.rb', line 10

def initialize(url)
  @url = url
  @rest = RestClient::Resource.new(@url)
  @version = 1
end

Instance Method Details

#call(action, params, raw: false) ⇒ Object



48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
# File 'lib/haveapi/client/communicator.rb', line 48

def call(action, params, raw: false)
  args = []
  input_namespace = action.namespace(:input)

  if %w(POST PUT).include?(action.http_method)
    args << {input_namespace => params}.to_json
    args << {:content_type => :json, :accept => :json}

  elsif %w(GET DELETE).include?(action.http_method)
    get_params = {}

    params.each do |k, v|
      get_params["#{input_namespace}[#{k}]"] = v
    end

    args << {params: get_params, accept: :json}
  end

  begin
    response = parse(@rest[action.prepared_url].method(action.http_method.downcase.to_sym).call(*args))

  rescue RestClient::Forbidden
    return error('Access forbidden. Bad user name or password? Not authorized?')

  rescue => e
    return error("Fatal API error: #{e.inspect}")
  end

  if response[:status]
    if raw
      ok(JSON.pretty_generate(response[:response]))
    else
      ok(response[:response])
    end

  else
    error(response[:message], response[:errors])
  end
end

#describe_action(v, r) ⇒ Object



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

def describe_action(v, r)

end

#describe_api(v = nil) ⇒ Object



20
21
22
# File 'lib/haveapi/client/communicator.rb', line 20

def describe_api(v=nil)
  description_for(path_for(v))
end

#get_action(resources, action, args) ⇒ Object



28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
# File 'lib/haveapi/client/communicator.rb', line 28

def get_action(resources, action, args)
  @spec ||= describe_api(@version)

  tmp = @spec

  resources.each do |r|
    tmp = tmp[:resources][r.to_sym]

    return false unless tmp
  end

  a = tmp[:actions][action]

  if a
    Action.new(self, action, a, args)
  else
    false
  end
end

#login(user, password) ⇒ Object



16
17
18
# File 'lib/haveapi/client/communicator.rb', line 16

def (user, password)
  @rest = RestClient::Resource.new(@url, user, password)
end