Created
September 20, 2011 23:09
-
-
Save panthomakos/1230704 to your computer and use it in GitHub Desktop.
Improved Custom Error Messages in Ruby
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
class Group | |
module Error | |
class Standard < StandardError; end | |
class AlreadyAMember < Standard; end | |
class NotPermittedToJoin < Standard; end | |
end | |
def join user | |
raise Error::NotPermittedToJoin unless self.permitted?(user) | |
raise Error::AlreadyAMember if self.member?(user) | |
self.members.create :user => user | |
end | |
end |
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 GroupErrorDisplay | |
@@errors = { | |
Group::Error::AlreadyAMember => "You are already a member of this group.", | |
Group::Error::NotPermittedToJoin => "You don't have the proper permissions to join this group." | |
} | |
def self.message(error) | |
@@errors[error.class] | |
end | |
end |
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
class GroupsController < ApplicationController | |
def join | |
@group = Group.find(params[:id]) | |
@group.join current_user | |
flash[:notice] = "Welcome to the Group!" | |
redirect_to @group | |
rescue Group::Error::Standard => exception | |
flash[:error] = GroupErrorDisplay.message(exception) | |
render :action => 'request' | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This is the improved version of this gist.