mkristian / kristians_rails_plugins

share my private rails plugins: fuzzy-search, datanmapper-session-store, idle-session-timeouts, etc

kristians_rails_plugins / act_as_fuzzy_search / README
100644 89 lines (51 sloc) 2.141 kb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
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
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
ActAsFuzzySearch
================
 
this plugin is inspired by the following blog entry
http://unirec.blogspot.com/2007/12/live-fuzzy-search-using-n-grams-in.html
it can add a fuzzy search to model. this search needs another table where all the
trigrams are stored but that table is hidden otherwise.
 
the whole plugins does not work with ActiveRecords, but for Datamapper !! to get it to work
for ActiveRecord only a few code places need to be changed, I marked the in the code #DM.
 
configuration
=============
 
add the following in the model class
 
  include FuzzySearch
 
  act_as_fuzzy_search :property1, :property1
  
where :property1, :property2 are the properties which are index for the fuzzy search. each property gets split into words (separator is the whitespaces)
 
if you define a methods returning a string
 
  def self.normalize(word)
 
before include the FuzzySearch than this method gets used to normlize any word. default is to downcast
the string (which does only work properly within ascii)
 
trigrams table
==============
 
the naming follows the convention
 
class <model_classname>Trigram
 
  property :id, Integer, :serial => true
 
  property :<model_lowercase>_id, Integer, :index => true
 
  property :token, String, :nullable => false, :length => 3, :index => true
 
end
 
example
=======
 
class UserTrigram
 
  include DataMapper::Resource
 
  property :id, Integer, :serial => true
 
  property :user_id, Integer, :index => true
 
  property :token, String, :nullable => false, :length => 3, :index => true
 
end
 
the model class looks like this
 
class User
 
  include DataMapper::Resource
 
  def self.normalize(word)
     #TODO something
     word.downcase
  end
 
  include FuzzySearch
 
  act_as_fuzzy_search :firstname, :surname
  
  property :id, Integer, :serial => true
 
  property :surname, String, :nullable => false , :format => /^[^<'&">]*$/, :length => 32
  property :firstname, String, :nullable => false , :format => /^[^<'&">]*$/, :length => 32
 
end
 
now you can create users and search them in a fuzzy manner like
 
  User.fuzzy_find("Heywy")
 
enjoy !!
 
Copyright (c) 2008 kristian, released under the MIT license