Class: Searchlogic::Search
- Inherits:
-
Object
- Object
- Searchlogic::Search
- Defined in:
- lib/searchlogic/search.rb
Overview
A class that acts like a model, creates attr_accessors for named_scopes, and then chains together everything when an “action” method is called. It basically makes implementing search forms in your application effortless:
search = User.search
search.username_like = "bjohnson"
search.all
Is equivalent to:
User.search(:username_like => "bjohnson").all
Is equivalent to:
User.username_like("bjohnson").all
Defined Under Namespace
Modules: Implementation Classes: UnknownConditionError
Instance Attribute Summary collapse
-
#conditions ⇒ Object
Returns a hash of the current conditions set.
-
#current_scope ⇒ Object
Returns the value of attribute current_scope.
-
#klass ⇒ Object
Returns the value of attribute klass.
Instance Method Summary collapse
-
#initialize(klass, current_scope, conditions = {}) ⇒ Search
constructor
Creates a new search object for the given class.
Constructor Details
#initialize(klass, current_scope, conditions = {}) ⇒ Search
Creates a new search object for the given class. Ex:
Searchlogic::Search.new(User, {}, {:username_like => "bjohnson"})
43 44 45 46 47 |
# File 'lib/searchlogic/search.rb', line 43 def initialize(klass, current_scope, conditions = {}) self.klass = klass self.current_scope = current_scope self.conditions = conditions if conditions.is_a?(Hash) end |
Dynamic Method Handling
This class handles dynamic methods through the method_missing method
#method_missing(name, *args, &block) ⇒ Object (private)
64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 |
# File 'lib/searchlogic/search.rb', line 64 def method_missing(name, *args, &block) if name.to_s =~ /(\w+)=$/ condition = $1.to_sym scope_name = normalize_scope_name($1) if scope?(scope_name) conditions[condition] = type_cast(args.first, cast_type(scope_name)) else raise UnknownConditionError.new(name) end elsif scope?(normalize_scope_name(name)) conditions[name] else scope = conditions.inject(klass.scoped(current_scope)) do |scope, condition| scope_name, value = condition scope_name = normalize_scope_name(scope_name) klass.send(scope_name, value) if !klass.respond_to?(scope_name) arity = klass.named_scope_arity(scope_name) if !arity || arity == 0 if value == true scope.send(scope_name) else scope end else scope.send(scope_name, value) end end scope.send(name, *args, &block) end end |
Instance Attribute Details
#conditions ⇒ Object
Returns a hash of the current conditions set.
50 51 52 |
# File 'lib/searchlogic/search.rb', line 50 def conditions @conditions end |
#current_scope ⇒ Object
Returns the value of attribute current_scope.
38 39 40 |
# File 'lib/searchlogic/search.rb', line 38 def current_scope @current_scope end |
#klass ⇒ Object
Returns the value of attribute klass.
38 39 40 |
# File 'lib/searchlogic/search.rb', line 38 def klass @klass end |