dstrelau (owner)

Forks

Revisions

gist: 86347 Download_button fork
public
Description:
Basic Hoptoad Notifier as Rack Middleware
Public Clone URL: git://gist.github.com/86347.git
Embed All Files: show embed
config.ru #
1
2
3
4
5
6
require 'rack/hoptoad_notifier'
 
use Rack::HoptoadNotifier do |config|
  config[:api_key] = 'XXXXXXXX'
end
 
hoptoad_notifier.rb #
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
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