refactor error messages and fix custom invalide type message

This commit is contained in:
Adam Meehan 2010-09-30 18:28:39 +10:00
parent 2be057b057
commit bd1b2f0b96
2 changed files with 15 additions and 6 deletions

View File

@ -44,23 +44,29 @@ module ValidatesTimeliness
value = parse(raw_value) if value.is_a?(String) || options[:format]
value = type_cast_value(value, @type)
return record.errors.add(attr_name, :"invalid_#{@type}") if value.blank?
if value.blank?
return add_error(record, attr_name, :"invalid_#{@type}")
end
@restrictions_to_check.each do |restriction|
begin
restriction_value = type_cast_value(evaluate_option_value(options[restriction], record), @type)
unless value.send(RESTRICTIONS[restriction], restriction_value)
return record.errors.add(attr_name, restriction, :message => options[:"#{restriction}_message"], :restriction => format_error_value(restriction_value))
return add_error(record, attr_name, restriction, format_error_value(restriction_value))
end
rescue => e
unless ValidatesTimeliness.ignore_restriction_errors
record.errors[attr_name] = "Error occurred validating #{attr_name} for #{restriction.inspect} restriction:\n#{e.message}"
add_error(record, attr_name, "Error occurred validating #{attr_name} for #{restriction.inspect} restriction:\n#{e.message}")
end
end
end
end
def add_error(record, attr_name, message, value=nil)
message_options = { :message => options[:"#{message}_message"], :restriction => value }
record.errors.add(attr_name, message, message_options)
end
def format_error_value(value)
format = I18n.t(@type, :default => DEFAULT_ERROR_VALUE_FORMATS[@type], :scope => 'validates_timeliness.error_value_formats')
value.strftime(format)

View File

@ -190,11 +190,14 @@ describe ValidatesTimeliness::Validator do
end
context "custom error message" do
it 'should be used for invalid type' do
Person.validates_date :birth_date, :invalid_date_message => 'custom invalid message'
invalid!(:birth_date, 'asdf', 'custom invalid message')
end
it 'should be used for failing restriction' do
it 'should be used for invalid restriction' do
Person.validates_date :birth_date, :before => Time.now, :before_message => 'custom before message'
invalid!(:birth_date, Time.now, 'custom before message')
end
end
end