module TkhSearch::TkhSearchable

Public Instance Methods

index_individual_record(record) click to toggle source
# File lib/tkh_search/tkh_searchable.rb, line 27
def index_individual_record(record)
  words = {}
  # Loop through each indexable field
  self.tkh_search_indexable_fields.each do |field_name, strength|
    # Remove html tags, transform to lowercase and split words
    # Splitting only with spaces because we want to preserve devanagari characters
    Sanitize.fragment(record.send(field_name)).downcase.split.each do |word|
      word = clean_up(word)
      if words[word] # add strength to existing word rating
        words[word] += strength
      else # new word
        words[word] = strength # create a new word pair
      end
    end
  end
  populate_index_tables( words, record )
end
reverse_indexing() click to toggle source
# File lib/tkh_search/tkh_searchable.rb, line 14
def reverse_indexing
  # Any model must have a self.tkh_search_indexable_fields class method returning
  # a hash of "field_name: :strength" pairs to be indexed
  if defined? self.tkh_search_indexable_fields
    # Index all records of the given model
    self.all.each do |record|
      index_individual_record(record)
    end
  else # no fields have been set in the model
    "The model '#{self.name}' has no fields marked for indexing."
  end
end
tkh_searchable() click to toggle source

Class methods

# File lib/tkh_search/tkh_searchable.rb, line 9
def tkh_searchable
  include TkhSearch::TkhSearchable::LocalInstanceMethods
  after_save :index_record
end

Private Instance Methods

clean_up(str) click to toggle source
# File lib/tkh_search/tkh_searchable.rb, line 47
def clean_up(str)
  str.strip.sub(/\,$/, '').sub(/\.$/, '').sub(/^\'/, '').sub(/\'$/, '').strip
end
populate_index_tables( words, record ) click to toggle source
# File lib/tkh_search/tkh_searchable.rb, line 51
def populate_index_tables( words, record )
  # populate tkh_search_terms and tkh_search_instances tables
  words.each do |word,strength|
    term = TkhSearchTerm.find_or_create_by( word: word )
    instance = TkhSearchInstance.find_or_create_by(
                host_model_name: self.name,
                model_record_id: record.id,
                tkh_search_term_id: term.id )
    instance.rating   = strength
    instance.language = I18n.locale
    defined?(record.published?) ? instance.published = record.published? : instance.published = false
    instance.save!
  end
end