Class: Tr8n::ApiClient

Inherits:
Base
  • Object
show all
Defined in:
lib/tr8n/api_client.rb

Constant Summary collapse

API_HOST =
'https://translationexchange.com'
API_PATH =
'/tr8n/api/'

Instance Attribute Summary

Attributes inherited from Base

#attributes

Class Method Summary collapse

Instance Method Summary collapse

Methods inherited from Base

attributes, belongs_to, has_many, #hash_value, hash_value, #initialize, #method_missing, #to_hash, #update_attributes

Constructor Details

This class inherits a constructor from Tr8n::Base

Dynamic Method Handling

This class handles dynamic methods through the method_missing method in the class Tr8n::Base

Class Method Details

.error?(data) ⇒ Boolean

Returns:

  • (Boolean)


65
66
67
# File 'lib/tr8n/api_client.rb', line 65

def self.error?(data)
  not data["error"].nil?
end

Instance Method Details

#access_tokenObject



41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
# File 'lib/tr8n/api_client.rb', line 41

def access_token
  application.access_token ||= begin
    api("oauth/request_token",
      {
          :client_id => application.key,
          :client_secret => application.secret,
          :grant_type => :client_credentials
      },
      {
          :host => application.host
      }
    )
  end
  application.access_token["access_token"]
end

#api(path, params = {}, opts = {}) ⇒ Object



81
82
83
84
85
86
87
88
89
90
# File 'lib/tr8n/api_client.rb', line 81

def api(path, params = {}, opts = {})
  if opts[:method] == :get and opts[:cache_key]
    data = Tr8n.cache.fetch(opts[:cache_key]) do
      execute_request(path, params, opts)
    end
    process_response(data, opts)
  else
    process_response(execute_request(path, params, opts), opts)
  end
end

#connectionObject



73
74
75
76
77
78
79
# File 'lib/tr8n/api_client.rb', line 73

def connection
  @connection ||= Faraday.new(:url => host) do |faraday|
    faraday.request(:url_encoded)               # form-encode POST params
    # faraday.response :logger                  # log requests to STDOUT
    faraday.adapter(Faraday.default_adapter)    # make requests with Net::HTTP
  end
end

#execute_request(path, params = {}, opts = {}) ⇒ Object

Raises:



92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
# File 'lib/tr8n/api_client.rb', line 92

def execute_request(path, params = {}, opts = {})
  response = nil
  error = nil

  Tr8n.logger.trace_api_call(path, params) do
    begin
      if opts[:method] == :post
        response = connection.post("#{API_PATH}#{path}", params)
      else
        response = connection.get("#{API_PATH}#{path}", params)
      end
    rescue Exception => ex
      Tr8n.logger.error("Failed to execute request: #{ex}")
      error = ex
      nil
    end
  end
  raise Tr8n::Exception.new("Error: #{error}") if error

  if response.status >= 500 and response.status < 600
    raise Tr8n::Exception.new("Error: #{response.body}")
  end

  begin
    data = JSON.parse(response.body)
  rescue Exception => ex
    raise Tr8n::Exception.new("Error: #{ex}")
  end

  unless data["error"].nil?
    raise Tr8n::Exception.new("Error: #{data["error"]}")
  end

  data
end

#get(path, params = {}, opts = {}) ⇒ Object



57
58
59
# File 'lib/tr8n/api_client.rb', line 57

def get(path, params = {}, opts = {})
  api(path, params.merge(:client_id => application.key, :t => Time.now.to_i), opts.merge(:method => :get))
end

#hostObject



69
70
71
# File 'lib/tr8n/api_client.rb', line 69

def host
  application.host || API_HOST
end

#object_class(opts) ⇒ Object



128
129
130
131
# File 'lib/tr8n/api_client.rb', line 128

def object_class(opts)
  return unless opts[:class]
  opts[:class].is_a?(String) ? opts[:class].constantize : opts[:class]
end

#post(path, params = {}, opts = {}) ⇒ Object



61
62
63
# File 'lib/tr8n/api_client.rb', line 61

def post(path, params = {}, opts = {})
  api(path, params.merge(:access_token => access_token, :t => Time.now.to_i), opts.merge(:method => :post))
end

#process_response(data, opts) ⇒ Object



133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
# File 'lib/tr8n/api_client.rb', line 133

def process_response(data, opts)
  if data["results"]
    Tr8n.logger.debug("received #{data["results"].size} result(s)")
    return data["results"] unless object_class(opts)
    objects = []
    data["results"].each do |data|
      objects << object_class(opts).new(data.merge(opts[:attributes] || {}))
    end
    return objects
  end

  return data unless object_class(opts)
  #Tr8n.logger.debug("constructing #{object_class(opts).name}")
  object_class(opts).new(data.merge(opts[:attributes] || {}))
end