Skip to content

Instantly share code, notes, and snippets.

@dstrelau
Created March 26, 2009 21:16
Show Gist options
  • Save dstrelau/86347 to your computer and use it in GitHub Desktop.
Save dstrelau/86347 to your computer and use it in GitHub Desktop.
Basic Hoptoad Notifier as Rack Middleware
require 'rack/hoptoad_notifier'
use Rack::HoptoadNotifier do |config|
config[:api_key] = 'XXXXXXXX'
end
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