Skip to content

Instantly share code, notes, and snippets.

@coderxin
Last active August 29, 2015 14:27
Show Gist options
  • Save coderxin/4caa229853c9ce27fea6 to your computer and use it in GitHub Desktop.
Save coderxin/4caa229853c9ce27fea6 to your computer and use it in GitHub Desktop.
Reduce validation messages
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
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
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