Created
December 28, 2011 18:28
-
-
Save paneq/1529034 to your computer and use it in GitHub Desktop.
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
class InvalidLengthError | |
attr_accessor :min, :max, :current | |
private :min=, :max=, :current= | |
CODE = "INVALID_LENGTH" | |
DESCRIPTION = "Invalid length" | |
def initialize(min, max, current) | |
self.min = min | |
self.max = max | |
self.current = current | |
end | |
def code | |
CODE | |
end | |
def description | |
DESCRIPTION | |
end | |
def empty? | |
false | |
end | |
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 'invalid_length_error' | |
class User < ActiveRecord::Base | |
validate :login_length | |
private | |
def login_length | |
return if login.size >= 2 && login.size <= 10 | |
errors.add(:login, InvalidLengthError.new(2, 10, login.size)) | |
end | |
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
module UsersHelper | |
def error_message(error) | |
return error if error.is_a?(String) # Message is just a string, we can't even try to do something nice with it | |
method = error.code.to_s.downcase + "_error_message" | |
return send(method, error) if respond_to?(method) # We have a special way of displaying such error | |
return error.description # Just display the description from model | |
end | |
def invalid_length_error_message(error) | |
"length of this text is invalid. Minimum is <strong>#{error.min}</strong> and maximum is <strong>#{error.max}</strong>".html_safe | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment