Module: Fuzzily::Model

Defined in:
lib/fuzzily/model.rb

Defined Under Namespace

Modules: ClassMethods

Class Method Summary collapse

Class Method Details

.included(by) ⇒ Object

Needs fields: trigram, owner_type, owner_id, score Needs index on [owner_type, trigram] and [owner_type, owner_id]



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
# File 'lib/fuzzily/model.rb', line 6

def self.included(by)
  by.ancestors.include?(ActiveRecord::Base) or raise 'Not included in an ActiveRecord subclass'

  scope_method = ActiveRecord::VERSION::MAJOR == 2 ? :named_scope : :scope

  by.class_eval do
    return if class_variable_defined?(:@@fuzzily_trigram_model)

    belongs_to :owner, :polymorphic => true
    validates_presence_of     :owner
    validates_uniqueness_of   :trigram, :scope => [:owner_type, :owner_id, :fuzzy_field]
    validates_length_of       :trigram, :is => 3
    validates_presence_of     :score
    validates_presence_of     :fuzzy_field

    send scope_method, :for_model,  lambda { |model| { 
      :conditions => { :owner_type => model.kind_of?(Class) ? model.name : model  } 
    }}
    send scope_method, :for_field,  lambda { |field_name| {
      :conditions => { :fuzzy_field => field_name }
    }}
    send scope_method, :with_trigram, lambda { |trigrams| {
      :conditions => { :trigram => trigrams }
    }}

    class_variable_set(:@@fuzzily_trigram_model, true)
  end

  by.extend(ClassMethods)
end