Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- require 'net/http'
- require 'json'
- require 'digest/md5'
- class RestApi
- include MproConfig
- include MproLogger
- def initialize(user)
- @user = user
- @args = []
- end
- def method_missing(method, *args)
- begin
- initialise_params
- convert_args_to_params(args.first)
- @params[:method] = method.to_s.gsub("_", ".")
- @params[:sig] = generate_sig
- escape_args
- response = send_request
- return response if response
- rescue Exception => exc
- MproLogger.mlog("#{@service_name} method call error: #{exc.message}")
- super
- end
- end
- private
- def initialise_params
- #should be overloaded
- end
- def convert_args_to_params(args)
- return unless args
- @args = []
- args.each do |k,v|
- @params[k] = case v
- when Array then v.join(',')
- else v.to_s
- end
- @args << k
- end
- end
- def escape_args
- @args.each do |k|
- @params[k] = CGI.escape(@params[k])
- end
- end
- def generate_sig
- @data = @params.
- sort{|a,b| a[0].to_s <=> b[0].to_s}.
- map{|arg| "#{arg[0]}=#{arg[1]}"}.
- join
- Digest::MD5.hexdigest(@sig.call)
- end
- def symbolize_keys(data)
- data = [data] if Hash === data
- return data unless Array === data
- response = []
- data.each do |item|
- response << case item
- when Array then
- symbolize_keys item
- when Hash then
- hash = {}
- item.each do |k,v|
- hash[k.to_sym] = Array === v ? symbolize_keys(v) : v
- end
- hash
- else item
- end
- end
- response.size == 1 ? response.first : response
- end
- def send_request
- query_string = @params.
- map{|arg| "#{arg[0]}=#{arg[1]}"}.
- join('&')
- http = Net::HTTP.new(@service_address, 80)
- path = "#{@service_path}?#{query_string}"
- resp, data = http.get(path)
- unless resp.code_type == Net::HTTPOK
- MproLogger.mlog("Bad response from #{@service_address}: #{resp.code}")
- return
- end
- attributes = JSON.parse(data)
- if Hash === attributes && attributes.has_key?("error")
- MproLogger.mlog("#{@service_name} request error: #{attributes['error'].inspect}")
- return
- end
- #puts attributes.inspect
- case attributes
- when Array then
- return symbolize_keys attributes
- when Hash then
- if attributes.has_key?("response")
- return symbolize_keys attributes["response"]
- else
- return symbolize_keys attributes
- end
- else return attributes
- end
- end
- end
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement