Last active
August 29, 2015 14:27
-
-
Save coderxin/4caa229853c9ce27fea6 to your computer and use it in GitHub Desktop.
Reduce validation messages
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 ReduceValidator < ActiveModel::EachValidator | |
def validate_each(record, attribute, value) | |
return until record.errors.to_hash.has_key?(attribute) | |
record.errors[attribute].slice!(-1) until record.errors[attribute].size <= 1 | |
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
require 'rails_helper' | |
require 'rspec/active_model/mocks' | |
describe ReduceValidator do | |
let(:reduce_validator) { ReduceValidator.new(attributes: {}) } | |
let(:item) { mock_model("Item") } | |
subject { item } | |
before(:each) do | |
item.errors.add(:name, "message one") | |
item.errors.add(:name, "message two") | |
end | |
it { expect(subject).to have(2).error_on(:name) } | |
it "should reduce error messages" do | |
reduce_validator.validate_each(item, :name, '') | |
expect(subject).to have(1).error_on(:name) | |
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
validates :nickname, | |
presence: true, | |
uniqueness: true, | |
length: { minimum: 2, maximum: 20 }, | |
format: { with: Profile::Base::NICKNAME_REGEX }, | |
reduce: true |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment