Skip to content

Instantly share code, notes, and snippets.

@joshnesbitt
Created July 16, 2015 13:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save joshnesbitt/d4a0e13562ed60dda73d to your computer and use it in GitHub Desktop.
Save joshnesbitt/d4a0e13562ed60dda73d to your computer and use it in GitHub Desktop.
module BannedWordFilter
class Filter
class << self
BANNED_WORDS = %w(
fuck
shit
banned
)
BANNED_WORDS_REGEX = /(#{BANNED_WORDS.join('|')})/i
def run!(text)
filtered = text.dup.gsub(BANNED_WORDS_REGEX) do |match|
first_char = match[0]
middle_chars = match[1...-1]
last_char = match[-1]
"#{first_char}#{'*' * middle_chars.size}#{last_char}"
end
Result.new(text, filtered)
end
end
end
class Result
def initialize(original, clean)
@original, @clean = original, clean
end
def original_text
@original
end
def clean_text
@clean
end
def clean?
@original == @clean
end
end
end
def log_result(r)
puts
puts "Original: #{r.original_text}"
puts "Cleaned: #{r.clean_text}"
puts "Clean?: #{r.clean?}"
puts
end
log_result(BannedWordFilter::Filter.run!("This is a sentence."))
log_result(BannedWordFilter::Filter.run!("This is a fucking sentence."))
log_result(BannedWordFilter::Filter.run!("This is a fucking sentence here's a shit."))
log_result(BannedWordFilter::Filter.run!("This is a fucking sentence here's a shit banned."))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment