datamapper / dm-validations

Library for performing validations on DM models and pure Ruby object
http://datamapper.org/
MIT License
50 stars 43 forks source link

Custom error messages for all inferred validations #66

Open nblumoe opened 11 years ago

nblumoe commented 11 years ago

I would like to use custom error messages for all inferred validations. What I want to do is shown in this spec (based on this):

 it "should have correct error messages" do
    custom_boat = Class.new do
      include DataMapper::Resource

      def self.name
        'Boat'
      end

      property :id,   DataMapper::Property::Serial
      property :length, Integer, :min => 1,
               :messages => {
                 :greater_than_or_equal_to => "Length must be at least 1"
               }
     end

    boat = custom_boat.new

    boat.length = 0
    boat.should_not be_valid
    boat.errors.on(:length).should == [ 'Length must be at least 1' ]

    boat.length = 3
    boat.should be_valid
    boat.errors.on(:length).should be_nil

As you can see I would like to override the default error message for the auto validation derived from :min => 1. Currently this spec fails:

'Inferred validations should have correct error messages' FAILED
expected: ["Length must be at least 1"],
     got: [#<DataMapper::Validation::Violation @resource=#<Boat @id=nil @name="superboat" @length=0> @rule=#<Dat
aMapper::Validation::Rule::Numericalness::GreaterThanOrEqual @attribute_name=:length @allow_nil=true @allow_blan
k=nil @custom_message=nil @if_clause=nil @unless_clause=nil @expected=1> @custom_message=nil @attribute_name=:le
ngth>] (using ==) 

Is there a good reason why boat.errors does not get a string attached due to the failed validation but this Violation instance instead? Does it make sense to change that?

I would love to provide a pull request if you think this change makes sense.

royaltm commented 10 years ago

+1

tillsc commented 9 years ago

The DataMapper::Validation::Violation#to_s method returns your expected result. If you replace

boat.errors.on(:length).should == [ 'Length must be at least 1' ]

with

boat.errors.on(:length).map(&:to_s).should == [ 'Length must be at least 1' ]

your example should work.