Skip to content
This repository has been archived by the owner on Oct 27, 2020. It is now read-only.

ResultFilter

aurelian edited this page Sep 13, 2010 · 2 revisions

The ResultFilter acts like an “interface” that will allow you to …well, filter the results. A special method, called valid? will be invoked on each result (if such a filter is given to the KeywordTree).

Although defined in the extension, this class can be translated to Ruby code:

module AhoCorasick
  class ResultFilter

    # result => current result, Hash
    # remain => what's left to be search, String
    def valid?(result, remain)
    end

  end
end

So, filtering the results can be done then by extending this class and overwriting the valid? implementation.

At your convenience, the current result as well as the remain —ing string to be searched are passed as arguments to valid?.

class FooNotAllowed < AhoCorasick::ResultFilter

  def valid?(result, remain)
    result[:value] != "foo"
  end

end

To attach a filter to the KeywordTree, use filter= method with your filter instance as argument.

Example:

Assuming a valid AhoCorasick::KeywordTree tree:

>> tree.filter= FooNotAllowed.new
=> #<FooNotAllowed:0x12d8a4c>
>> tree.add_string "foo"
=> 1
>> tree.add_string "bar"
=> 2
>> tree.add_string "baz"
=> 3
>> results= tree.find_all("foo is not bar")
=> [{:ends_at=>14, :starts_at=>11, :value=>"bar", :id=>2}]
Clone this wiki locally