Module: PhatPgsearch::ActiveRecord::SingletonMethods

Defined in:
lib/phat_pgsearch/active_record.rb

Overview

:nodoc:

Instance Method Summary collapse

Instance Method Details

#pgsearch(*args) ⇒ Object



28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
# File 'lib/phat_pgsearch/active_record.rb', line 28

def pgsearch(*args)
  options = args.extract_options!
  normalization = options.delete(:normalization) || 32
  rank = options.delete(:rank)

  scope = self

  search_query = pgsearch_query(args.first, args.second, options)

  if args.first.is_a? Symbol or args.first.to_s.split('.', 2) == 1
    vector_column = "#{self.connection.quote_table_name(self.table_name)}.#{self.connection.quote_column_name(args.first.to_s)}"
  else
    vector_column = args.first.split('.', 2).collect{ |f| self.connection.quote_column_name(f) }.join('.')
  end

  if rank.nil? or rank == true
    scope = scope.select("#{self.connection.quote_table_name(self.table_name)}.*, ts_rank_cd(#{vector_column}, #{search_query}, #{normalization.to_i}) AS rank")
  end

  scope.where("#{vector_column} @@ #{search_query}")
end

#pgsearch_definitionsObject



24
25
26
# File 'lib/phat_pgsearch/active_record.rb', line 24

def pgsearch_definitions
  @pgsearch_definitions
end

#pgsearch_query(*args) ⇒ Object

Raises:

  • (ArgumentError)


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
# File 'lib/phat_pgsearch/active_record.rb', line 50

def pgsearch_query(*args)
  options = args.extract_options!
  plain = options.delete(:plain) || true
  match = options.delete(:matchall)  == true ? " && " : " || "
  raise ArgumentError, "invalid field given" if args.first.nil? or not (args.first.is_a? String or args.first.is_a? Symbol)
  raise ArgumentError, "invalid query given" if args.second.nil? or not (args.second.is_a? String)

  field = args.first.to_s.split(".", 2)

  table_class = self

  if field.count == 2
    begin
      table_class = field.first.classify.constantize
    rescue
      raise ArgumentError, "unknown table in field given"
    end
  end

  raise ArgumentError, "table has no index defined" unless table_class.respond_to? :pgsearch_definitions
  raise ArgumentError, "table has no index defined for '#{field.last.to_sym}'" if table_class.pgsearch_definitions[field.last.to_sym].nil?


  definition = table_class.pgsearch_definitions[field.last.to_sym]
  if definition
    catalog = options[:catalog] || definition.catalog
  else
    catalog = options[:catalog] || definition.catalog
  end

  words = args.second.split(/ +/)
  search_words = words.collect do |word|
    "#{plain ? 'plain' : ''}to_tsquery(#{self.sanitize(catalog)}, #{self.sanitize(word)})"
  end

  "(#{search_words.join(match)})"
end

#rebuild_pgindex!Object

rebuild complete index for model



89
90
91
# File 'lib/phat_pgsearch/active_record.rb', line 89

def rebuild_pgindex!
  self.all.each { |model| model.rebuild_pgindex! }
end