Class: Trenni::Words::Filter
- Inherits:
-
Object
- Object
- Trenni::Words::Filter
- Defined in:
- lib/trenni/words/filter.rb
Overview
Filters patterns from a block of text.
Class Method Summary collapse
- .for_obscenity ⇒ Object
- .load_file(path) ⇒ Object
-
.regexp_from_wildcard(string) ⇒ Object
Convert a string into a regexp.
Instance Method Summary collapse
- #=~(text) ⇒ Object
- #apply(text) ⇒ Object
-
#initialize(patterns) ⇒ Filter
constructor
A new instance of Filter.
- #replace(match) ⇒ Object
Constructor Details
#initialize(patterns) ⇒ Filter
Returns a new instance of Filter.
25 26 27 |
# File 'lib/trenni/words/filter.rb', line 25 def initialize(patterns) @patterns = Regexp.union(*patterns) end |
Class Method Details
.for_obscenity ⇒ Object
58 59 60 |
# File 'lib/trenni/words/filter.rb', line 58 def self.for_obscenity @obscenity_filter ||= self.load_file(File.("obscenity.txt", __dir__)) end |
.load_file(path) ⇒ Object
50 51 52 53 54 55 56 |
# File 'lib/trenni/words/filter.rb', line 50 def self.load_file(path) patterns = File.readlines(path).collect do |line| self.regexp_from_wildcard(line.chomp!) end Filter.new(patterns) end |
.regexp_from_wildcard(string) ⇒ Object
Convert a string into a regexp. If the string starts with a ‘/`, it’s considered a raw regexp.
42 43 44 45 46 47 48 |
# File 'lib/trenni/words/filter.rb', line 42 def self.regexp_from_wildcard(string) if string.start_with? '/' return Regexp.new(string[1...-1], Regexp::IGNORECASE) else return Regexp.new('\b' + string + '\b', Regexp::IGNORECASE) end end |
Instance Method Details
#=~(text) ⇒ Object
37 38 39 |
# File 'lib/trenni/words/filter.rb', line 37 def =~ text @patterns =~ text end |
#apply(text) ⇒ Object
33 34 35 |
# File 'lib/trenni/words/filter.rb', line 33 def apply(text) text.gsub(@patterns, &self.method(:replace)) end |
#replace(match) ⇒ Object
29 30 31 |
# File 'lib/trenni/words/filter.rb', line 29 def replace(match) '*' * match.length end |