Module: ActsAsFuzzySearch::Fuzzy::ClassMethods

Defined in:
lib/acts_as_fuzzy_search/fuzzy.rb

Constant Summary collapse

DEFAULT_ALGORITHM =
:white_similarity
MATCH_SCORE =

used by jarow-winkler and white-similarity

0.8
MIN_LEVENSHTEIN_DISTANCE =

number of changes to get the strings to match

3
DATE_FORMAT =
"%B %d %Y"
SCOPE =
"all"

Instance Attribute Summary collapse

Instance Method Summary collapse

Instance Attribute Details

#configObject

Returns the value of attribute config.



20
21
22
# File 'lib/acts_as_fuzzy_search/fuzzy.rb', line 20

def config
  @config
end

Instance Method Details

#acts_as_fuzzy_search(options = {}) ⇒ Object



22
23
24
25
26
27
28
29
30
31
32
# File 'lib/acts_as_fuzzy_search/fuzzy.rb', line 22

def acts_as_fuzzy_search(options = {})
  @config = { :date_format => DATE_FORMAT,
              :scope => "all",
              :search_algorithm => DEFAULT_ALGORITHM,
              :jarow_score => MATCH_SCORE,
              :white_similarity_score => MATCH_SCORE,
              :min_levenshtein_distance => MIN_LEVENSHTEIN_DISTANCE,
              :debug => false }

  @config.merge!(options)
end

#find_by_fuzzy_search(search_term, options = {}) ⇒ Object



34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
# File 'lib/acts_as_fuzzy_search/fuzzy.rb', line 34

def find_by_fuzzy_search(search_term, options = {})
  
  @config.merge!(options)

  search_term = search_term.strip.chomp
  records = []

  send(config[:scope]).each do |record|

    attrs = record.attributes.values

    # convert dates to ones humans will likely search on
    attrs.collect! {|a| ([Date,Time,DateTime].include? a.class) ? a.strftime(config[:date_format]) : a }

    # 'create' an html page
    markup = Nokogiri::HTML(attrs.join(" "))

    # strip all the tags and whitespace
    no_tags = markup.text.gsub(/\s+|\n/, ' ')
  
    # Match each word in the document against each search term
    no_tags.split(" ").each do |word|        
       search_term.split(" ").each do |term|
         records << record if matches?(term, word)
       end
     end
  end
  return records.uniq
end