Created
March 26, 2009 21:16
-
-
Save dstrelau/86347 to your computer and use it in GitHub Desktop.
Basic Hoptoad Notifier as Rack Middleware
This file contains hidden or 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
require 'rack/hoptoad_notifier' | |
use Rack::HoptoadNotifier do |config| | |
config[:api_key] = 'XXXXXXXX' | |
end |
This file contains hidden or 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
require 'net/http' | |
module Rack | |
class HoptoadNotifier | |
attr_reader :config | |
def initialize(app) | |
@app = app | |
@config = { | |
:api_key => '' | |
} | |
yield @config if block_given? | |
end | |
def call(env) | |
status, headers, body = | |
begin | |
@app.call(env) | |
rescue => boom | |
send_notification boom, env | |
raise | |
end | |
[status, headers, body] | |
end | |
private | |
def stringify_keys(hash) #:nodoc: | |
hash.inject({}) do |h, pair| | |
h[pair.first.to_s] = pair.last.is_a?(Hash) ? stringify_keys(pair.last) : pair.last | |
h | |
end | |
end | |
def send_notification(exception, env) | |
headers = { | |
'Content-type' => 'application/x-yaml', | |
'Accept' => 'text/xml, application/xml' | |
} | |
url = URI.parse "http://hoptoadapp.com/notices" | |
http = Net::HTTP.new(url.host, url.port) | |
http.read_timeout = 5 | |
http.open_timeout = 2 | |
data = { | |
:api_key => config[:api_key], | |
:error_message => "#{exception.class}: #{exception}", | |
:backtrace => exception.backtrace, | |
:request => {}, | |
:session => env['rack.session'], | |
:environment => env | |
} | |
response = begin | |
http.post(url.path, stringify_keys(:notice => data).to_yaml, headers) | |
rescue TimeoutError => e | |
puts "Timeout while contacting the Hoptoad server." | |
nil | |
end | |
case response | |
when Net::HTTPSuccess then | |
puts "Hoptoad Success: #{response.class}\n#{response.body if response.respond_to? :body}" | |
else | |
puts "Hoptoad Failure: #{response.class}\n#{response.body if response.respond_to? :body}" | |
end | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment