Class: English::Filter

Inherits:
Object show all
Defined in:
lib/gems/english-0.3.1/lib/english/textfilter.rb

Overview

:nodoc:

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initializeFilter

Returns a new instance of Filter.



24
25
26
27
# File 'lib/gems/english-0.3.1/lib/english/textfilter.rb', line 24

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

Instance Attribute Details

#rulesObject (readonly)

Returns the value of attribute rules.



18
19
20
# File 'lib/gems/english-0.3.1/lib/english/textfilter.rb', line 18

def rules
  @rules
end

#word_rulesObject (readonly)

Returns the value of attribute word_rules.



20
21
22
# File 'lib/gems/english-0.3.1/lib/english/textfilter.rb', line 20

def word_rules
  @word_rules
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)


74
75
76
77
78
79
80
81
# File 'lib/gems/english-0.3.1/lib/english/textfilter.rb', line 74

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.



58
59
60
61
62
63
64
# File 'lib/gems/english-0.3.1/lib/english/textfilter.rb', line 58

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



85
86
87
# File 'lib/gems/english-0.3.1/lib/english/textfilter.rb', line 85

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.



36
37
38
39
# File 'lib/gems/english-0.3.1/lib/english/textfilter.rb', line 36

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' }


50
51
52
53
# File 'lib/gems/english-0.3.1/lib/english/textfilter.rb', line 50

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