Skip to content

Instantly share code, notes, and snippets.

@mpj
Created July 29, 2010 08:40
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mpj/497636 to your computer and use it in GitHub Desktop.
Save mpj/497636 to your computer and use it in GitHub Desktop.
class JayCutCommandFactory
attr_accessor :site_name, :key, :secret, :api_host_base
def initialize(site_name, key, secret)
@site_name = site_name
@key = key
@secret = secret
@api_host_base = "api.jaycut.com"
end
def create(method, path)
JayCutCommand.new(self, method, path)
end
end
class JayCutCommand
attr_accessor :factory, :method, :path, :expires
def initialize(factory, method, path)
raise "Path must begin with slash." if path[0] != 47
raise "Factory cannot be nil" if factory.nil?
if (method.upcase != "PUT" and method.upcase != "GET" and method.upcase != "POST" and method.upcase != "DELETE")
raise ArgumentError, "Method must be PUT, DELETE, GET or POST", method
@factory = factory
@method = method.upcase
@path = path
@expires = Time.now.to_i + 3600
end
def uri
# Returns the uri for the command
URI.parse( "http://" + @factory.site_name + "." + @factory.api_host_base + @path )
end
def uri_with_authentication
# Returns the uri for the command, including authentication query string
uri = uri.to_s + "?" + query_string
method_hack = "&_method=" + @method
# some clients (such as flash, and explorer) have an issue with PUT and delete methods. This insures that the right format gets through.
URI.parse( uri + method_hack )
end
def uri_with_authentication_and_login
# Same as uri_with_authentication, but also includes a login parameter, setting a cookie on the client.
URI.parse( uri_with_querystring.to_s + "&login=true" )
end
def query_string
"api_key=" + @factory.key +
"&signature=" + generate_signature() +
"&expires=" + @expires.to_s
end
def run
req = Net::HTTP::Put.new(uri.path)
req.body = query_string
res = Net::HTTP.start(url.host, url.port) { |http|
http.request(req)
}
res.body
end
def generate_signature()
base = @factory.secret + @method + @path + @expires.to_s
Digest::SHA1.hexdigest base
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment