Imagine you're writing an application that allows multiple types of user accounts.
All users have a username, and no user should be allowed to choose a name that contains profanity.
At first, you duplicate the validation across all models:
class User < ActiveRecord::Base
BAD_WORDS = %w(darn gosh heck golly)
validate :username_does_not_contain_profanity
private
def username_does_not_contain_profanity
if BAD_WORDS.any? { |word| username.include?(word) }
errors.add(:username, "cannot contain naughty words!")
end
end
end
class Admin < ActiveRecord::Base
validate :username_does_not_contain_profanity
private
def username_does_not_contain_profanity
if BAD_WORDS.any? { |word| username.include?(word) }
errors.add(:username, "cannot contain naughty words!")
end
end
end
How can we reuse this validation and remove the duplication?