Skip to content

Instantly share code, notes, and snippets.

@JoshMcKin
Created February 3, 2011 16:42
Show Gist options
  • Save JoshMcKin/809746 to your computer and use it in GitHub Desktop.
Save JoshMcKin/809746 to your computer and use it in GitHub Desktop.
Early EventMachine Zendesk example
module EmZendesk
require 'em-http'
class Base < SimpleModel::Base
has_attributes :zen_resource, :params, :username, :password, :response, :company_url
has_attributes :format, :default => 'json'
has_attributes :http_method, :default => :post
validate :validates_post_response
def params_for_request
{self.zen_resource.singularize => self.params}
end
def save
self.fetch_response
self.valid?
end
def fetch_response
if EM::reactor_running?
self.response = self.send(self.http_method).response
else
EM.run {
http = self.send(self.http_method)
http.errback { failed }
http.callback {
self.response = http.response
EM.stop
}
}
end
end
def post
EM::HttpRequest.new("http://#{self.company_url}.zendesk.com/#{self.zen_resource}.#{self.format}").post :body => self.params_for_request,
:head => {'authorization' => [self.username,self.password]}
end
private
def validates_post_response
errors.add(:response, "error. #{self.response}") unless self.response.blank?
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment