Created
February 3, 2011 16:42
-
-
Save JoshMcKin/809746 to your computer and use it in GitHub Desktop.
Early EventMachine Zendesk example
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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