merb_exceptions 0.9.8

Sign up to get free protection for your applications and to get access to all the features.
data/LICENSE ADDED
@@ -0,0 +1,20 @@
1
+ Copyright (c) 2008 New Bamboo
2
+
3
+ Permission is hereby granted, free of charge, to any person obtaining
4
+ a copy of this software and associated documentation files (the
5
+ "Software"), to deal in the Software without restriction, including
6
+ without limitation the rights to use, copy, modify, merge, publish,
7
+ distribute, sublicense, and/or sell copies of the Software, and to
8
+ permit persons to whom the Software is furnished to do so, subject to
9
+ the following conditions:
10
+
11
+ The above copyright notice and this permission notice shall be
12
+ included in all copies or substantial portions of the Software.
13
+
14
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
15
+ EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
16
+ MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
17
+ NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
18
+ LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
19
+ OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
20
+ WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
@@ -0,0 +1,105 @@
1
+ merb_exceptions
2
+ ===============
3
+ A simple Merb plugin to ease exception notifications.
4
+
5
+ The notifier currently supports two interfaces, Email Alerts and Web Hooks. Emails are formatted as plain text and sent using your Merb environment's mail settings. Web hooks as sent as post requests.
6
+
7
+ Instead of a messy port of a rails plugin this is a complete rewrite from scratch and so is able to take full advantage of Merb's exception handling functionality.
8
+
9
+ Getting Going
10
+ -------------
11
+ Once you have the Gem installed you will need to add it as a dependency in your projects `init.rb` file
12
+
13
+ dependency 'merb_exceptions'
14
+
15
+ Configuration goes in `config/plugins.yml` file (which you may need to create). See 'Settings' below for a full description of the options.
16
+
17
+ :exceptions:
18
+ :app_name: My App Name
19
+ :email_from: exceptions@myapp.com
20
+ :web_hooks: http://localhost:4000/exceptions
21
+ :email_addresses:
22
+ - user@myapp.com
23
+ - hello@exceptions.com
24
+ :environments:
25
+ - staging
26
+ - production
27
+
28
+ The plugin now automatically includes itself into your Exceptions controller. If you are using an old version of this plugin, you can remove the include from your Exceptions controller.
29
+
30
+ If you have specified any email addresses, and are not already requiring merb-mailer, then you need to do so. It also needs configuration.
31
+
32
+ dependency 'merb-mailer'
33
+
34
+ Settings
35
+ --------
36
+ `web_hooks`, `email_addresses`, and `environments` can either be a single string or an array of strings.
37
+
38
+ `app_name`: Used to customise emails and web hooks (default "My App")
39
+
40
+ `email_from`: Exceptions are sent from this address
41
+
42
+ `web_hooks`: Each url is sent a post request. See 'Web Hooks' for more info.
43
+
44
+ `email_addresses`: Each email address is sent an exception notification using Merb's built in mailer settings.
45
+
46
+ `environments`: Notifications will only be sent for environments in this list, defaults to `production`
47
+
48
+ Advanced usage
49
+ --------------
50
+ Including `MerbExceptions::ControllerExtensions` creates an `internal_server_error` action which renders the default exception page and delivers the exception. If you need to rescue any other exceptions or customize the behavior in any way you can write your own actions in `ExceptionsController` and make a call to `render_and_notify`.
51
+
52
+ For example to be notified of 404's:
53
+
54
+ def not_found
55
+ render_and_notify :format => :html
56
+ end
57
+
58
+ `render_and_notify` - passes any provided options directly to Merb's render method and then sends the notification after rendering.
59
+
60
+ `notify_of_exceptions` - if you need to handle the render yourself for some reason then you can call this method directly. It sends notifications without any rendering logic. Note though that if you are sending lots of notifications this could delay sending a response back to the user so try to avoid using it where possible.
61
+
62
+ Web hooks
63
+ ---------
64
+ Web hooks are a great way to push your data beyond your app to the outside world. For each address on your `web_hooks` list we will send a HTTP:POST request with the following parameters for you to consume.
65
+
66
+ WEBHOOKS FORMATTING IS CURRENTLY BROKEN. WILL POST AN EXAMPLE OF THE CORRECT FORMAT HERE WHEN IT'S FIXED.
67
+
68
+ Requirements
69
+ ------------
70
+ * Edge Merb
71
+
72
+ Install
73
+ -------
74
+ Install gem from github
75
+
76
+ sudo gem install newbamboo-merb_exceptions --source=http://gems.github.com
77
+
78
+ or install from source with
79
+
80
+ rake install_gem
81
+
82
+ Licence
83
+ -------
84
+ (The MIT License)
85
+
86
+ Copyright (c) 2008 New Bamboo
87
+
88
+ Permission is hereby granted, free of charge, to any person obtaining
89
+ a copy of this software and associated documentation files (the
90
+ 'Software'), to deal in the Software without restriction, including
91
+ without limitation the rights to use, copy, modify, merge, publish,
92
+ distribute, sublicense, and/or sell copies of the Software, and to
93
+ permit persons to whom the Software is furnished to do so, subject to
94
+ the following conditions:
95
+
96
+ The above copyright notice and this permission notice shall be
97
+ included in all copies or substantial portions of the Software.
98
+
99
+ THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND,
100
+ EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
101
+ MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
102
+ IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
103
+ CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
104
+ TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
105
+ SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
@@ -0,0 +1,80 @@
1
+ require 'rubygems'
2
+ require 'rake/gempackagetask'
3
+ require "rake/rdoctask"
4
+ require 'merb-core/tasks/merb_rake_helper'
5
+ require "spec/rake/spectask"
6
+
7
+ PLUGIN = "merb_exceptions"
8
+ GEM_NAME = "merb_exceptions"
9
+ AUTHOR = 'Andy Kent'
10
+ EMAIL = "andy@new-bamboo.co.uk"
11
+ HOMEPAGE = "http://merb-plugins.rubyforge.org/me/"
12
+ SUMMARY = "Allows Merb to forward exceptions to emails or web hooks"
13
+
14
+ RUBY_FORGE_PROJECT = "merb"
15
+ PROJECT_URL = "http://merbivore.com"
16
+ PROJECT_SUMMARY = "Allows Merb to forward exceptions to emails or web hooks"
17
+ PROJECT_DESCRIPTION = PROJECT_SUMMARY
18
+
19
+
20
+ GEM_AUTHOR = 'Andy Kent'
21
+ GEM_EMAIL = "andy@new-bamboo.co.uk"
22
+
23
+ GEM_NAME = "merb_exceptions"
24
+ PKG_BUILD = ENV['PKG_BUILD'] ? '.' + ENV['PKG_BUILD'] : ''
25
+ GEM_VERSION = (Merb::MORE_VERSION rescue "0.9.8") + PKG_BUILD
26
+
27
+ RELEASE_NAME = "REL #{GEM_VERSION}"
28
+
29
+ require "extlib/tasks/release"
30
+
31
+ spec = Gem::Specification.new do |s|
32
+ s.name = GEM_NAME
33
+ s.version = GEM_VERSION
34
+ s.platform = Gem::Platform::RUBY
35
+ s.has_rdoc = true
36
+ s.extra_rdoc_files = ["LICENSE"]
37
+ s.summary = SUMMARY
38
+ s.description = s.summary
39
+ s.author = AUTHOR
40
+ s.email = EMAIL
41
+ s.homepage = HOMEPAGE
42
+ s.require_path = 'lib'
43
+ s.autorequire = PLUGIN
44
+ s.files = %w(LICENSE README.markdown Rakefile) + Dir.glob("{lib,spec}/**/*")
45
+ end
46
+
47
+ Rake::GemPackageTask.new(spec) do |pkg|
48
+ pkg.gem_spec = spec
49
+ end
50
+
51
+ ##############################################################################
52
+ # Installation
53
+ ##############################################################################
54
+ desc "Install the gem"
55
+ task :install do
56
+ Merb::RakeHelper.install(GEM_NAME, :version => GEM_VERSION)
57
+ end
58
+
59
+ desc "Uninstall the gem"
60
+ task :uninstall do
61
+ Merb::RakeHelper.uninstall(GEM_NAME, :version => GEM_VERSION)
62
+ end
63
+
64
+ ##############################################################################
65
+ # Specs
66
+ ##############################################################################
67
+ desc "Run all specs"
68
+ Spec::Rake::SpecTask.new("specs") do |t|
69
+ t.spec_opts = ["--format", "specdoc", "--colour"]
70
+ t.spec_files = Dir["spec/**/*_spec.rb"].sort
71
+ end
72
+
73
+ desc "Run all specs and generate an rcov report"
74
+ Spec::Rake::SpecTask.new('rcov') do |t|
75
+ t.spec_files = FileList['spec/**/*_spec.rb']
76
+ t.spec_opts = ["--format", "specdoc", "--colour"]
77
+ t.rcov = true
78
+ t.rcov_dir = 'coverage'
79
+ t.rcov_opts = ['--exclude', 'gems', '--exclude', 'spec']
80
+ end
@@ -0,0 +1,25 @@
1
+ # make sure we're running inside Merb
2
+ if defined?(Merb::Plugins)
3
+
4
+ # Default configuration
5
+ Merb::Plugins.config[:exceptions] = {
6
+ :web_hooks => [],
7
+ :email_addresses => [],
8
+ :app_name => "Merb awesome Application",
9
+ :email_from => "exceptions@app.com",
10
+ :environments => ['production']
11
+ }.merge(Merb::Plugins.config[:exceptions] || {})
12
+
13
+ Merb::BootLoader.before_app_loads do
14
+
15
+ end
16
+
17
+ Merb::BootLoader.after_app_loads do
18
+ if Merb::Plugins.config[:exceptions][:environments].include?(Merb.env)
19
+ Exceptions.send(:include, MerbExceptions::ControllerExtensions)
20
+ end
21
+ end
22
+
23
+ require "merb_exceptions/notification"
24
+ require 'merb_exceptions/controller_extensions'
25
+ end
@@ -0,0 +1,41 @@
1
+ module MerbExceptions
2
+ module ControllerExtensions
3
+
4
+ def self.included(mod)
5
+ mod.class_eval do
6
+ def base
7
+ self.render_and_notify template_or_message, :layout=>false
8
+ end
9
+
10
+ def exception
11
+ self.render_and_notify template_or_message, :layout=>false
12
+ end
13
+
14
+ private
15
+
16
+ def template_or_message
17
+ if File.exists?(Merb.root / 'app' / 'views' / 'exceptions' / 'internal_server_error.html.erb')
18
+ :internal_server_error
19
+ else
20
+ '500 exception. Please customize this page by creating app/views/exceptions/internal_server_error.html.erb.'
21
+ end
22
+ end
23
+ end
24
+ end
25
+
26
+ def render_and_notify(*opts)
27
+ self.render_then_call(render(*opts)) { notify_of_exceptions }
28
+ end
29
+
30
+ def notify_of_exceptions
31
+ request = self.request
32
+
33
+ details = {}
34
+ details['exceptions'] = request.exceptions
35
+ details['params'] = params
36
+ details['environment'] = request.env.merge( 'process' => $$ )
37
+ details['url'] = "#{request.protocol}#{request.env["HTTP_HOST"]}#{request.uri}"
38
+ MerbExceptions::Notification.new(details).deliver!
39
+ end
40
+ end
41
+ end
@@ -0,0 +1,103 @@
1
+ require 'net/http'
2
+ require 'uri'
3
+ require "erb"
4
+
5
+ module MerbExceptions
6
+ class Notification
7
+ attr_reader :details
8
+
9
+ def initialize(details = nil)
10
+ @details = details || {}
11
+ @config = Merb::Plugins.config[:exceptions]
12
+ end
13
+
14
+ def deliver!
15
+ deliver_web_hooks!
16
+ deliver_emails!
17
+ end
18
+
19
+ def deliver_web_hooks!
20
+ return unless should_deliver_notifications?
21
+ Merb.logger.info "DELIVERING EXCEPTION WEB HOOKS"
22
+ web_hooks.each do |address|
23
+ post_hook(address)
24
+ end
25
+ end
26
+
27
+ def deliver_emails!
28
+ return unless should_deliver_notifications?
29
+ Merb.logger.info "DELIVERING EXCEPTION EMAILS"
30
+ email_addresses.each do |address|
31
+ send_notification_email(address)
32
+ end
33
+ end
34
+
35
+ def web_hooks; option_as_array(:web_hooks); end
36
+
37
+ def email_addresses; option_as_array(:email_addresses); end
38
+
39
+ def environments; option_as_array(:environments); end
40
+
41
+
42
+ def should_deliver_notifications?
43
+ environments.include? Merb.env
44
+ end
45
+
46
+
47
+ def params
48
+ {
49
+ 'request_url' => details['url'],
50
+ 'request_controller' => details['params'][:controller],
51
+ 'request_action' => details['params'][:action],
52
+ 'request_params' => details['params'],
53
+ 'environment' => details['environment'],
54
+ 'exceptions' => details['exceptions'],
55
+ 'app_name' => @config[:app_name]
56
+ }
57
+ end
58
+
59
+ private
60
+
61
+ def post_hook(address)
62
+ Merb.logger.info "- hooking to #{address}"
63
+ uri = URI.parse(address)
64
+ uri.path = '/' if uri.path=='' # set a path if one isn't provided to keep Net::HTTP happy
65
+ Net::HTTP.post_form( uri, params ).body
66
+ end
67
+
68
+ def send_email(address, body)
69
+ Merb.logger.info "- emailing to #{address}"
70
+ email = Merb::Mailer.new({
71
+ :to => address,
72
+ :from => @config[:email_from],
73
+ :subject => "[#{@config[:app_name]} EXCEPTION]",
74
+ :text => body
75
+ })
76
+ email.deliver!
77
+ end
78
+
79
+ def send_notification_email(address)
80
+ send_email(address, plain_text_mail_body)
81
+ end
82
+
83
+ def plain_text_mail_body
84
+ path = File.join(File.dirname(__FILE__), 'templates', 'email.erb')
85
+ template = Erubis::Eruby.new(File.open(path,'r') { |f| f.read })
86
+ template.result(binding)
87
+ end
88
+
89
+ # Used so that we can accept either a single value or array (e.g. of
90
+ # webhooks) in our YAML file.
91
+ def option_as_array(option)
92
+ value = @config[option]
93
+ case value
94
+ when Array
95
+ value.reject { |e| e.nil? } # Don't accept nil values
96
+ when String
97
+ [value]
98
+ else
99
+ []
100
+ end
101
+ end
102
+ end
103
+ end
@@ -0,0 +1,38 @@
1
+ <% params['exceptions'].each do |e| %>
2
+ EXCEPTION
3
+ ----------
4
+ <% if e.respond_to?(:name) %>
5
+ Name: <%= e.name.to_s.split("_").map {|x| x.capitalize}.join(" ") %>
6
+ <% end %>
7
+ <% if e.respond_to?(:status) %>
8
+ Status Code: <%= e.status %>
9
+ <% end %>
10
+ Merb Exception Class: <%= e.class %>
11
+ Message: <%= e.message %>
12
+
13
+
14
+ BACKTRACE
15
+ ----------
16
+ <%= (e.backtrace || []).join("\n") %>
17
+
18
+
19
+ <% end %>
20
+ REQUEST
21
+ --------
22
+ URL: <%= params['request_url'] %>
23
+ Controller: <%= params['request_controller'] %>
24
+ Action: <%= params['request_action'] %>
25
+
26
+
27
+ PARAMETERS
28
+ -----------
29
+ <% params['request_params'].each do |key,value| %>
30
+ <%= key %>: <%= value %>
31
+ <% end %>
32
+
33
+
34
+ ENVIRONMENT
35
+ ------------
36
+ <% params['environment'].each do |key,value| %>
37
+ <%= key %>: <%= value %>
38
+ <% end %>
@@ -0,0 +1,84 @@
1
+ require File.dirname(__FILE__) + '/spec_helper'
2
+
3
+ include MerbExceptions
4
+ include NotificationSpecHelper
5
+
6
+ describe MerbExceptions::Notification do
7
+ describe "#new" do
8
+ it "should create a new notification without errors" do
9
+ lambda { Notification.new(mock_details) }.should_not raise_error
10
+ end
11
+
12
+ it "should set the detail values to those provided" do
13
+ Notification.new(mock_details).details.should == mock_details
14
+ end
15
+ end
16
+
17
+ describe ".deliver!" do
18
+ before :each do
19
+ @notification = Notification.new(mock_details)
20
+ @notification.stub!('deliver_emails!')
21
+ @notification.stub!('deliver_web_hooks!')
22
+ end
23
+
24
+ it "should deliver web hooks" do
25
+ @notification.should_receive('deliver_web_hooks!')
26
+ @notification.deliver!
27
+ end
28
+
29
+ it "should deliver emails" do
30
+ @notification.should_receive('deliver_emails!')
31
+ @notification.deliver!
32
+ end
33
+ end
34
+
35
+ describe ".deliver_web_hooks!" do
36
+ before :each do
37
+ mock_merb_config({:web_hooks => ['http://www.test1.com', 'http://www.test2.com']})
38
+ @notification = Notification.new(mock_details)
39
+ @notification.stub!(:post_hook)
40
+ end
41
+
42
+ it "should call post_hook for each url" do
43
+ @notification.should_receive(:post_hook).
44
+ once.with('http://www.test1.com')
45
+ @notification.should_receive(:post_hook).
46
+ once.with('http://www.test2.com')
47
+ @notification.deliver_web_hooks!
48
+ end
49
+ end
50
+
51
+ describe ".deliver_emails!" do
52
+ before :each do
53
+ mock_merb_config({:email_addresses => ['user1@test.com', 'user2@test.com']})
54
+ @notification = Notification.new(mock_details)
55
+ @notification.stub!(:send_notification_email)
56
+ end
57
+
58
+ it "should call send_notification_email for each address" do
59
+ @notification.should_receive(:send_notification_email).
60
+ once.with('user1@test.com')
61
+ @notification.should_receive(:send_notification_email).
62
+ once.with('user2@test.com')
63
+ @notification.deliver_emails!
64
+ end
65
+ end
66
+
67
+ # Running tests with test environment
68
+ describe ".should_deliver_notifications?" do
69
+ it "should return true if the current environment is on the config[:environments] list of one item" do
70
+ mock_merb_config({ :environments => 'test' })
71
+ Notification.new(mock_details).should_deliver_notifications?.should be_true
72
+ end
73
+
74
+ it "should return true if the current environment is on the config[:environments] list as an array" do
75
+ mock_merb_config({ :environments => ['staging', 'test'] })
76
+ Notification.new(mock_details).should_deliver_notifications?.should be_true
77
+ end
78
+
79
+ it "should return false if the current environment is not on the config[:environments] list" do
80
+ mock_merb_config({ :environments => ['staging', 'development'] })
81
+ Notification.new(mock_details).should_deliver_notifications?.should be_false
82
+ end
83
+ end
84
+ end
@@ -0,0 +1,26 @@
1
+ $:.unshift File.join(File.dirname(__FILE__), '..', 'lib')
2
+ require "rubygems"
3
+ require "merb-core"
4
+ require "spec"
5
+ require "merb_exceptions"
6
+
7
+ # merb-exceptions needs to include itself into this class
8
+ class Exceptions < Merb::Controller; end
9
+
10
+ Merb::Plugins.config[:exceptions][:environments] = 'test'
11
+ Merb.start :environment => 'test'
12
+
13
+ module NotificationSpecHelper
14
+ def mock_details(opts={})
15
+ {
16
+ 'exception' => {},
17
+ 'params' => { :controller=>'errors', :action=>'show' },
18
+ 'environment' => { 'key1'=>'value1', 'key2'=>'value2' },
19
+ 'url' => 'http://www.my-app.com/errors/1'
20
+ }.merge(opts)
21
+ end
22
+
23
+ def mock_merb_config(opts={})
24
+ Merb::Plugins.config[:exceptions].merge!(opts)
25
+ end
26
+ end
metadata ADDED
@@ -0,0 +1,63 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: merb_exceptions
3
+ version: !ruby/object:Gem::Version
4
+ version: 0.9.8
5
+ platform: ruby
6
+ authors:
7
+ - Andy Kent
8
+ autorequire: merb_exceptions
9
+ bindir: bin
10
+ cert_chain: []
11
+
12
+ date: 2008-10-07 00:00:00 +03:00
13
+ default_executable:
14
+ dependencies: []
15
+
16
+ description: Allows Merb to forward exceptions to emails or web hooks
17
+ email: andy@new-bamboo.co.uk
18
+ executables: []
19
+
20
+ extensions: []
21
+
22
+ extra_rdoc_files:
23
+ - LICENSE
24
+ files:
25
+ - LICENSE
26
+ - README.markdown
27
+ - Rakefile
28
+ - lib/merb_exceptions
29
+ - lib/merb_exceptions/controller_extensions.rb
30
+ - lib/merb_exceptions/notification.rb
31
+ - lib/merb_exceptions/templates
32
+ - lib/merb_exceptions/templates/email.erb
33
+ - lib/merb_exceptions.rb
34
+ - spec/notification_spec.rb
35
+ - spec/spec_helper.rb
36
+ has_rdoc: true
37
+ homepage: http://merb-plugins.rubyforge.org/me/
38
+ post_install_message:
39
+ rdoc_options: []
40
+
41
+ require_paths:
42
+ - lib
43
+ required_ruby_version: !ruby/object:Gem::Requirement
44
+ requirements:
45
+ - - ">="
46
+ - !ruby/object:Gem::Version
47
+ version: "0"
48
+ version:
49
+ required_rubygems_version: !ruby/object:Gem::Requirement
50
+ requirements:
51
+ - - ">="
52
+ - !ruby/object:Gem::Version
53
+ version: "0"
54
+ version:
55
+ requirements: []
56
+
57
+ rubyforge_project:
58
+ rubygems_version: 1.2.0
59
+ signing_key:
60
+ specification_version: 2
61
+ summary: Allows Merb to forward exceptions to emails or web hooks
62
+ test_files: []
63
+