Skip to content

Instantly share code, notes, and snippets.

@dhh
Last active May 8, 2020 11:19
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dhh/10649506 to your computer and use it in GitHub Desktop.
Save dhh/10649506 to your computer and use it in GitHub Desktop.
# 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