Module: Texticle

Defined in:
lib/texticle.rb,
lib/texticle/rails.rb

Defined Under Namespace

Modules: Helper Classes: Railtie

Instance Method Summary collapse

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

#method_missing(method, *search_terms) ⇒ Object



32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
# File 'lib/texticle.rb', line 32

def method_missing(method, *search_terms)
  return super if self == ActiveRecord::Base
  if Helper.dynamic_search_method?(method, self.columns)
    exclusive = Helper.exclusive_dynamic_search_method?(method, self.columns)
    columns = exclusive ? Helper.exclusive_dynamic_search_columns(method) : Helper.inclusive_dynamic_search_columns(method)
    metaclass = class << self; self; end
    metaclass.__send__(:define_method, method) do |*args|
      query = columns.inject({}) do |query, column|
        query.merge column => args.shift
      end
      search(query, exclusive)
    end
    __send__(method, *search_terms, exclusive)
  else
    super
  end
end

Instance Method Details

#respond_to?(method, include_private = false) ⇒ Boolean

Returns:

  • (Boolean)


50
51
52
53
# File 'lib/texticle.rb', line 50

def respond_to?(method, include_private = false)
  return super if self == ActiveRecord::Base
  Helper.dynamic_search_method?(method, self.columns) ? true : super
end

#search(query = "", exclusive = true) ⇒ Object



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
# File 'lib/texticle.rb', line 5

def search(query = "", exclusive = true)
  language = connection.quote('english')

  unless query.is_a?(Hash)
    exclusive = false
    query = searchable_columns.inject({}) do |terms, column|
      terms.merge column => query.to_s
    end
  end

  similarities = []
  conditions = []

  query.each do |column, search_term|
    column = connection.quote_column_name(column)
    search_term = connection.quote normalize(Helper.normalize(search_term))
    similarities << "ts_rank(to_tsvector(#{quoted_table_name}.#{column}), to_tsquery(#{search_term}))"
    conditions << "to_tsvector(#{language}, #{column}) @@ to_tsquery(#{search_term})"
  end

  rank = connection.quote_column_name('rank' + rand.to_s)

  select("#{quoted_table_name + '.*,' if scoped.select_values.empty?} #{similarities.join(" + ")} AS #{rank}").
    where(conditions.join(exclusive ? " AND " : " OR ")).
    order("#{rank} DESC")
end