Module: AttrSearchable::ClassMethods

Defined in:
lib/attr_searchable.rb

Instance Method Summary collapse

Instance Method Details

#attr_searchable(*args) ⇒ Object



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

def attr_searchable(*args)
  args.each do |arg|
    attr_searchable_hash arg.is_a?(Hash) ? arg : { arg => arg }
  end
end

#attr_searchable_alias(hash) ⇒ Object



70
71
72
73
74
# File 'lib/attr_searchable.rb', line 70

def attr_searchable_alias(hash)
  hash.each do |key, value|
    self.searchable_attribute_aliases[key.to_s] = value.respond_to?(:table_name) ? value.table_name : value.to_s
  end
end

#attr_searchable_hash(hash) ⇒ Object



56
57
58
59
60
61
62
63
64
# File 'lib/attr_searchable.rb', line 56

def attr_searchable_hash(hash)
  hash.each do |key, value|
    self.searchable_attributes[key.to_s] = Array(value).collect do |column|
      table, attribute = column.to_s =~ /\./ ? column.to_s.split(".") : [name.tableize, column]

      "#{table}.#{attribute}"
    end
  end
end

#attr_searchable_options(key, options = {}) ⇒ Object



66
67
68
# File 'lib/attr_searchable.rb', line 66

def attr_searchable_options(key, options = {})
  self.searchable_attribute_options[key.to_s] = (searchable_attribute_options[key.to_s] || {}).merge(options)
end

#search(query) ⇒ Object



76
77
78
79
80
# File 'lib/attr_searchable.rb', line 76

def search(query)
  unsafe_search query
rescue AttrSearchable::RuntimeError
  respond_to?(:none) ? none : where("1 = 0")
end

#unsafe_search(query) ⇒ Object



82
83
84
85
86
87
88
89
90
91
# File 'lib/attr_searchable.rb', line 82

def unsafe_search(query)
  return respond_to?(:scoped) ? scoped : all if query.blank?

  associations = searchable_attributes.values.flatten.uniq.collect { |column| column.split(".").first }.collect { |column| searchable_attribute_aliases[column] || column.to_sym }

  scope = respond_to?(:search_scope) ? search_scope : nil
  scope ||= eager_load(associations - [name.tableize.to_sym])

  scope.where AttrSearchable::Parser.parse(query, self).optimize!.to_sql(self)
end