class Baidu::Aip::Base

Constants

TOKEN_URL

Attributes

client[RW]

Public Instance Methods

get_params() click to toggle source
# File lib/baidu/aip/base.rb, line 20
def get_params
  custom_params.merge intrinsic_params
end
get_token() click to toggle source
# File lib/baidu/aip/base.rb, line 42
def get_token
  if client.access_token && from_now(hour(1)) < client.expire_time
    client.access_token
  else
    token_hash = {
      :grant_type => 'client_credentials',
      :client_id => client.api_key,
      :client_secret => client.secret_key
    }

    begin
      token_response = RestClient.post "#{TOKEN_URL}?#{build_url(token_hash)}", {}, {}
      json = JSON(token_response.body)
      client.access_token = json['access_token']
      client.expire_time = Time.now + json['expires_in']
      client.access_token
    rescue RestClient::ExceptionWithResponse => e
      log e.response
      return nil
    end
  end
end
headers() click to toggle source
# File lib/baidu/aip/base.rb, line 28
def headers
  {accept: :json}
end
post_params() click to toggle source
# File lib/baidu/aip/base.rb, line 24
def post_params
  {}
end
process() click to toggle source
# File lib/baidu/aip/base.rb, line 32
def process
  begin
    response = RestClient.post "#{service_url}?#{build_url(get_params)}", post_params, headers
    JSON(response.body)
  rescue RestClient::ExceptionWithResponse => e
    log e.response
    JSON(e.response.body)
  end
end
service_url() click to toggle source
# File lib/baidu/aip/base.rb, line 15
def service_url
  name = underscore(self.class.name.sub('Baidu::Aip::', '').sub('::', '')).upcase
  self.class.const_get(name)
end

Protected Instance Methods

ago(seconds) click to toggle source
# File lib/baidu/aip/base.rb, line 93
def ago(seconds)
  Time.now - seconds
end
build_url(hash) click to toggle source
# File lib/baidu/aip/base.rb, line 66
def build_url(hash)
  hash.map{|k,v|"#{encode(k.to_s)}=#{encode(v.to_s)}"}.join('&')
end
custom_params() click to toggle source
# File lib/baidu/aip/base.rb, line 74
def custom_params
  {}
end
encode(str) click to toggle source
# File lib/baidu/aip/base.rb, line 70
def encode(str)
  ERB::Util.url_encode str
end
from_now(seconds) click to toggle source
# File lib/baidu/aip/base.rb, line 89
def from_now(seconds)
  Time.now + seconds
end
hour(num) click to toggle source
# File lib/baidu/aip/base.rb, line 85
def hour(num)
  3600 * num
end
intrinsic_params() click to toggle source
# File lib/baidu/aip/base.rb, line 78
def intrinsic_params
  {
    :access_token => get_token,
    :aipSdk => 'ruby',
  }
end
log(text) click to toggle source
# File lib/baidu/aip/base.rb, line 97
def log(text)
  puts text
  Rails.logger.info(text) if defined? Rails
end
underscore(str) click to toggle source
# File lib/baidu/aip/base.rb, line 102
def underscore(str)
  str.gsub(/::/, '/').
  gsub(/([A-Z]+)([A-Z][a-z])/,'\1_\2').
  gsub(/([a-z\d])([A-Z])/,'\1_\2').
  tr("-", "_").
  downcase
end