Class: Language::Censor

Inherits:
Object
  • Object
show all
Defined in:
lib/language/censor.rb

Overview

Censor

This class allows one to define a resuable text filter. This is useful for removing or replacing curse words or senstive information from user input.

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initializeCensor

New Censor object.



26
27
28
29
30
31
32
33
# File 'lib/language/censor.rb', line 26

def initialize()
  @rules = []
  @word_rules = []

  self.class.default_words.each do |word|
     word_rule(word)
  end
end

Instance Attribute Details

#rulesObject (readonly)

Abritraty rules.



19
20
21
# File 'lib/language/censor.rb', line 19

def rules
  @rules
end

#word_rulesObject (readonly)

Word-oriented rules.



22
23
24
# File 'lib/language/censor.rb', line 22

def word_rules
  @word_rules
end

Class Method Details

.default_wordsObject

Default censor list.



14
15
16
# File 'lib/language/censor.rb', line 14

def self.default_words
  []
end

Instance Method Details

#censored?(string) ⇒ Boolean

Is the string clear of any matching rules?

Note that running a filter does not necessarily clear a a string of all matches, since the filter could apply edits that would also match the filter expressions.

Returns:

  • (Boolean)


80
81
82
83
84
85
86
87
# File 'lib/language/censor.rb', line 80

def censored?(string)
  case string
  when *matches
    false
  else
    true
  end
end

#filter(string) ⇒ Object Also known as: apply

Apply the set of rules (regular expression matches) to a string.



64
65
66
67
68
69
70
# File 'lib/language/censor.rb', line 64

def filter(string)
  rewritten_string = string.dup
  rules.each do |match,edit|
    rewritten_string.gsub!(match,edit)
  end
  return (rewritten_string or string)
end

#matchesObject



91
92
93
# File 'lib/language/censor.rb', line 91

def matches
  rules.collect{ |match, modify| match }
end

#rule(match, &edit) ⇒ Object

Create new rule. A rule consists of a string or regexp to match against.

NOTE: The rules must be applied in order! So we cannot use a hash because the ordering is not guaranteed. So an array is used instead.



42
43
44
45
# File 'lib/language/censor.rb', line 42

def rule(match, &edit)
  edit = lambda{''} unless edit
  @rules << [match, edit]
end

#word_rule(match, &edit) ⇒ Object

Rules that apply only to words. This takes the regular expression and add word boundry matches to either side.

filter.word_rule(/damn/){ |w| 'darn' }

Is equivalent to teh regular rule:

filter.rule(/\bdamn\b/){ |w| 'darn' }


56
57
58
59
# File 'lib/language/censor.rb', line 56

def word_rule(match, &edit)
  edit = lambda{''} unless edit
  @word_rules << [/\b#{match}\b/, edit]
end