Module: SearchCop::ClassMethods

Defined in:
lib/search_cop.rb

Instance Method Summary collapse

Instance Method Details

#search_cop(query, scope_name, query_options) ⇒ Object



55
56
57
58
59
# File 'lib/search_cop.rb', line 55

def search_cop(query, scope_name, query_options)
  unsafe_search_cop(query, scope_name, query_options)
rescue SearchCop::RuntimeError
  respond_to?(:none) ? none : where("1 = 0")
end

#search_reflection(scope_name) ⇒ Object



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

def search_reflection(scope_name)
  search_scopes[scope_name].reflection
end

#search_scope(name, &block) ⇒ Object



41
42
43
44
45
46
47
48
49
# File 'lib/search_cop.rb', line 41

def search_scope(name, &block)
  self.search_scopes = search_scopes.dup

  search_scopes[name] = SearchScope.new(name, self)
  search_scopes[name].instance_exec(&block)

  send(:define_singleton_method, name) { |query, query_options = {}| search_cop(query, name, query_options) }
  send(:define_singleton_method, "unsafe_#{name}") { |query, query_options = {}| unsafe_search_cop(query, name, query_options) }
end

#unsafe_search_cop(query, scope_name, query_options) ⇒ Object



61
62
63
64
65
66
67
68
69
70
# File 'lib/search_cop.rb', line 61

def unsafe_search_cop(query, scope_name, query_options)
  return respond_to?(:scoped) ? scoped : all if query.blank?

  query_builder = QueryBuilder.new(self, query, search_scopes[scope_name], query_options)

  scope = instance_exec(&search_scopes[scope_name].reflection.scope) if search_scopes[scope_name].reflection.scope
  scope ||= eager_load(query_builder.associations) if query_builder.associations.any?

  (scope || self).where(query_builder.sql)
end