Skip to content

Instantly share code, notes, and snippets.

@alloy
Created August 17, 2009 23:10
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 alloy/169438 to your computer and use it in GitHub Desktop.
Save alloy/169438 to your computer and use it in GitHub Desktop.
require 'osx/cocoa'
require 'cgi'
class CocoaGist < OSX::NSObject
REQUEST_URL = OSX::NSURL.URLWithString('http://gist.github.com/gists')
TIMEOUT = 10
POLICY = 1 # NSURLRequestReloadIgnoringLocalCacheData
attr_accessor :delegate
attr_reader :connection, :response
def self.credentials
@credentials ||= {
'login' => `git config --global github.user`.strip,
'token' => `git config --global github.token`.strip
}.reject { |_, v| v.empty? }
end
def start(content, syntax = 'ruby')
request = post_request(params(content, syntax))
@connection = OSX::NSURLConnection.alloc.initWithRequest_delegate(request, self)
end
def cancel
if @connection
@connection.cancel
@connection = nil
end
end
def connection_willSendRequest_redirectResponse(_, request, response)
if response && response.statusCode == 302
@delegate.pastie_on_success(self, request.URL.absoluteString)
nil
else
request
end
end
def connection_didFailWithError(_, error)
@delegate.pastie_on_error(self, error.userInfo[:NSLocalizedDescription].to_s)
end
private
def post_request(body)
request = OSX::NSMutableURLRequest.requestWithURL_cachePolicy_timeoutInterval(REQUEST_URL, POLICY, TIMEOUT)
request.setHTTPMethod('POST')
request.setHTTPBody(OSX::NSData.dataWithRubyString(body))
request
end
def params(content, syntax)
self.class.credentials.merge({
'file_contents[gistfile1]' => content,
'file_ext[gistfile1]' => syntax_ext(syntax)
}).inject('') { |body, (key, value)| body << "#{key}=#{CGI.escape(value)}&" }.chop
end
def syntax_ext(syntax)
SYNTAX_TO_EXT[syntax.downcase]
end
SYNTAX_TO_EXT = {
'c' => '.h',
'css' => '.css',
'diff' => '.diff',
'haskell' => '.hs',
'html' => '.htm',
'java' => '.java',
'javascript' => '.js',
'objective-c' => '.m',
'perl' => '.pl',
'php' => '.php',
'plain text' => '.txt',
'python' => '.py',
'ruby' => '.rb',
'scheme' => '.scm',
'shell script' => '.sh',
'sql' => '.sql'
}
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment