Skip to content

Instantly share code, notes, and snippets.

@zhangyuan
Created October 3, 2012 18:32
Show Gist options
  • Save zhangyuan/3828857 to your computer and use it in GitHub Desktop.
Save zhangyuan/3828857 to your computer and use it in GitHub Desktop.
Taobao API parameters handler module.
# encoding: utf-8
# include Taobao::Parameters module, then call #params=() instance method to set more parameters ( method_name, etc.) and call
# #params_after_sign to get the full url query parameters after signing.
require 'digest/md5'
module Taobao
module Parameters
def self.included(base)
base.class_eval do
attr_writer :timestamp
attr_accessor :method_name
attr_writer :params
end
base.extend ClassMethods
base.send :include, InstanceMethods
end
module InstanceMethods
def default_params
{
:method => method_name,
:session => nil,
:timestamp => timestamp,
:format => format,
:app_key => self.class.app_key,
:v => 2.0,
:sign_method => :md5,
:pid => self.class.pid
}
end
def params
@params ||= {}
end
def params_before_sign
parameters = default_params.merge(params)
parameters.delete_if {|name, value| value.nil?}
parameters
end
def params_after_sign
params_before_sign.merge(:sign => self.class.sign(params_before_sign))
end
def format
:json
end
def timestamp
if @timestamp && @timestamp.is_a?(String)
@timestamp
else
(@timestamp ||= Time.now).strftime("%Y-%m-%d %H:%M:%S")
end
end
end
module ClassMethods
def app_secret
"" # TODO taobao api secret
end
def app_key
"" # TODO taobao api key
end
def pid
"" # TODO PID
end
def sign(options = {})
str = options.keys.sort.map do |name|
"#{name}#{options[name]}"
end.join
str = [app_secret, str, app_secret].join
Digest::MD5.hexdigest(str).upcase
end
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment