module UnpSmart::UnpSmartMethod

Attributes

api[RW]
config[RW]
debug[RW]
http_method[RW]
params[RW]
verbose[RW]

Public Class Methods

extended(base) click to toggle source
# File lib/unp_smart/unp_smart_method.rb, line 7
def self.extended(base)
  base.send :load_config
end

Public Instance Methods

_invoke_api(http_method,api,params={}) { |return_response| ... } click to toggle source
# File lib/unp_smart/unp_smart_method.rb, line 19
def _invoke_api http_method,api,params={}
  log "request api:#{api},params:#{params}"
  raise 'api is not allowed blank!' if api.blank?
  
  @api = api
  @params = params
  @http_method = http_method
  @debug = get_variable :debug
  @config = {} if @config.nil?
  @verbose = get_variable :verbose
  
  @api = "/#{@api}" unless @api.start_with?("/")
  
  account = get_variable :account
  log "account:", account if @verbose
  raise 'account is not allowed blank!' if account.blank?

  secret_key = get_variable :secret_key
  log "secret_key:",secret_key if @verbose
  
  raise 'invalid secret_key!' if secret_key.blank?
  
  extracted_params = request_params(params)
  extracted_params[:account] = account
  extracted_params[:source] = 'ruby-sdk'
  extracted_params[:timestamp] =Time.now.to_f
  extracted_params[:version] = '1.0'

  extracted_params[:sign] =  sign_params extracted_params,secret_key

  request_url = "#{get_variable :server}#{@api}?#{extracted_params.map{|key,value| "#{key}=#{CGI.escape value.nil? ? "" : value.to_s}"}.join("&")}"

  log "request:",request_url if @debug

  return_response = JSON.parse RestClient::Request.execute(url: request_url,
                                                        method: http_method,
                                                    verify_ssl:  false,
                                                       timeout: get_variable(:timeout))

  log "response:",return_response if @debug

  if block_given?
    log "invoke block" if @debug
    yield return_response
  else
    if get_variable(:raw_response)
      log "return raw response" if @verbose
      return_response
    else     
      log "parse result" 
      if return_response['resCode'] == '0000'
        return true,return_response
      else
        return false,"##{return_response['resCode']}:#{return_response['resMsg']}"
      end
    end
  end      
 # rescue => e
  # log "!!!invoke http service error",e.inspect
  # return false,e.message
end
get(api,params={}) click to toggle source
# File lib/unp_smart/unp_smart_method.rb, line 11
def get api,params={}
  _invoke_api :get,api,params
end
load_config() click to toggle source
# File lib/unp_smart/unp_smart_method.rb, line 93
def load_config
  log "loading config"
  path = "#{app_root}/config/unp_smart.yml"
  unless File.exist?(path)
    path = "#{File.expand_path('~')}/.unp_smart.yml"
    log "try use home config #{path}" if @verbose
    
    unless File.exist?(path)
      log "can't load config,will use env or params config"
      return
    end
  end
  log "config file path",path
  @config ||= YAML.load_file(path)[current_env]
  log "config:#{@config}" if @verbose
rescue => e
  log "load config error:#{e.inspect}"
end
post(api,params={}) click to toggle source
# File lib/unp_smart/unp_smart_method.rb, line 15
def post api,params={}
  _invoke_api :post,api,params
end
request_params(params={}) click to toggle source
# File lib/unp_smart/unp_smart_method.rb, line 89
def request_params params={}
  params.except(:action, :controller,:api_id,:id,:api_list,:format,:sign,:user,:source,:timestamp,:version,:secret_key)
end
sign_params(params,secret_key) click to toggle source
# File lib/unp_smart/unp_smart_method.rb, line 81
def sign_params params,secret_key
  sign_str = "#{params.sort_by { |k, v| k.to_s }.flatten.join}#{secret_key}"
  log "sign str",sign_str if @verbose
  Digest::MD5.hexdigest(sign_str).upcase.tap do |str|
    log "sign",str if @verbose
  end
end

Private Instance Methods

app_root() click to toggle source
# File lib/unp_smart/unp_smart_method.rb, line 139
def app_root
  root = Rails.root if rails_app?
  root.present? ? root : '.'
rescue => e
  log "access rails root got error:#{e.message}"
  '.'
end
current_env() click to toggle source
# File lib/unp_smart/unp_smart_method.rb, line 147
def current_env
  rails_app? ? Rails.env : (ENV['UNPSMART_ENV'].presence||'development')
end
get_variable(key) click to toggle source
# File lib/unp_smart/unp_smart_method.rb, line 113
def get_variable key
  get_variable_from_params(key).presence || 
     get_variable_from_env(key).presence ||
  get_variable_from_config(key)
end
get_variable_from_config(key) click to toggle source
# File lib/unp_smart/unp_smart_method.rb, line 127
def get_variable_from_config key
  @config[key.to_s] if @config.present?
end
get_variable_from_env(key) click to toggle source
# File lib/unp_smart/unp_smart_method.rb, line 123
def get_variable_from_env key
  ENV[key.to_s]||ENV["#{key.to_s}_#{current_env}"]
end
get_variable_from_params(key) click to toggle source
# File lib/unp_smart/unp_smart_method.rb, line 119
def get_variable_from_params key
  @params[key.to_sym] if @params.present?
end
log(*msg) click to toggle source
# File lib/unp_smart/unp_smart_method.rb, line 131
def log *msg
  file, line, _ = caller.first.split(":")
  messages = "#{file.split("/").last}:#{line}:#{msg.join("  ")}"

  @logger ||= rails_app? ? Logger.new("#{app_root}/log/api.log") : Logger.new(STDOUT)
  @logger.debug messages
end
rails_app?() click to toggle source
# File lib/unp_smart/unp_smart_method.rb, line 151
def rails_app?
  defined?(Rails)
end