Skip to content

Instantly share code, notes, and snippets.

@dhh dhh/profanity.rb
Last active Jun 4, 2019

Embed
What would you like to do?
# 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
You can’t perform that action at this time.