class XapianDb::Adapters::BaseAdapter

base class for all adapters. This adapter does the following:

@author Gernot Kogler

Public Class Methods

add_class_helper_methods_to(klass) click to toggle source

Implement the class helper methods @param [Class] klass The class to add the helper methods to

   # File lib/xapian_db/adapters/base_adapter.rb
17 def add_class_helper_methods_to(klass)
18 
19   klass.class_eval do
20 
21     # Add a method to search models of this class
22     # Options:
23     # - :order          (Array<Symbol>) Accepts an array of attribute names for sorting
24     # - :sort_decending (Boolean)       Allows to reverse the sorting
25     define_singleton_method(:search) do |expression, options={}|
26 
27       # return an empty search if no search expression is given
28       return XapianDb.database.search(nil) if expression.nil? || expression.strip.empty?
29 
30       options = {:sort_decending => false}.merge options
31       class_scope = "indexed_class:#{klass.name.downcase}"
32 
33       order = options.delete :order
34       if order
35         attr_names             = [order].flatten
36         undefined_attrs        = attr_names - XapianDb::DocumentBlueprint.attributes
37         raise ArgumentError.new "invalid order clause: attributes #{undefined_attrs.inspect} are not defined" unless undefined_attrs.empty?
38         options[:sort_indices] = attr_names.map {|attr_name| XapianDb::DocumentBlueprint.value_number_for(attr_name) }
39       end
40       result = XapianDb.database.search "#{class_scope} AND (#{expression})", options
41 
42       # Remove the class scope from the spelling suggestion (if any)
43       if result.spelling_suggestion
44         scope_length = "#{class_scope} AND (".size
45         result.spelling_suggestion = result.spelling_suggestion.slice scope_length..-2
46       end
47       result
48     end
49 
50     define_singleton_method(:find_similar_to) do |reference|
51      return XapianDb.database.find_similar_to reference, :class => klass
52     end
53 
54     # Add a method to search atribute facets of this class
55     define_singleton_method(:facets) do |attribute, expression|
56       class_scope  = "indexed_class:#{klass.name.downcase}"
57       XapianDb.database.facets attribute, "#{class_scope} and (#{expression})"
58     end
59 
60   end
61 end