Last active
May 8, 2020 11:19
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
# Option A: I'd start with this | |
class Micropost < ActiveRecord::Base | |
validate :no_profanity | |
private | |
def no_profanity | |
if user.minor? && profanity = profane_words_used_in_content | |
errors.add :content, "Profanity: '#{profanity.join(", ")}' not allowed!" | |
end | |
end | |
def profane_words_used_in_content | |
content.split(/\W/).select { |word| word.in? Rails.configuration.x.profane_words }.presence | |
end | |
end | |
# config/initializers/profanity.rb (using custom_configuration gem) | |
Rails.configuration.x.profane_words = %w( | |
poop | |
crap | |
) | |
# Option B: If you are going with an external class, at least use the validation framework | |
class Micropost < ActiveRecord::Base | |
validates_with NoProfanity | |
end | |
class NoProfanity < ActiveModel::Validator | |
def validate(post) | |
if post.user.minor? && (profanity = profane_words_used(post)).any? | |
post.errors.add :content, "Profanity: '#{profanity.join(", ")}' not allowed!" | |
end | |
end | |
private | |
def profane_words_used(post) | |
post.content.split(/\W/).select { |word| word.in? Rails.configuration.x.profane_words } | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment