Module: AttrSearchable::ClassMethods

Defined in:
lib/attr_searchable.rb

Instance Method Summary collapse

Instance Method Details

#attr_searchable(*args) ⇒ Object



52
53
54
55
56
# File 'lib/attr_searchable.rb', line 52

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



72
73
74
75
76
# File 'lib/attr_searchable.rb', line 72

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



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

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



68
69
70
# File 'lib/attr_searchable.rb', line 68

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

#default_searchable_attributesObject



78
79
80
81
82
83
84
# File 'lib/attr_searchable.rb', line 78

def default_searchable_attributes
  keys = searchable_attribute_options.select { |key, value| value[:default] == true }.keys
  keys = searchable_attributes.keys.reject { |key| searchable_attribute_options[key] && searchable_attribute_options[key][:default] == false } if keys.empty?
  keys = keys.to_set

  searchable_attributes.select { |key, value| keys.include? key }
end

#search(query) ⇒ Object



86
87
88
89
90
# File 'lib/attr_searchable.rb', line 86

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

#unsafe_search(query) ⇒ Object



92
93
94
95
96
97
98
99
100
101
# File 'lib/attr_searchable.rb', line 92

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