Permalink
Browse files

Adding a LikeQuery search scope to do LIKE database queries

  • Loading branch information...
1 parent 2d18c06 commit 56d0fd23422fe72671bcfe932ff46789dc4bfabb @towski towski committed Jul 30, 2008
Showing with 34 additions and 14 deletions.
  1. +19 −0 lib/can_search/like_query_scope.rb
  2. +15 −14 lib/can_search/search_scopes.rb
@@ -0,0 +1,19 @@
+module CanSearch
+ # Generates a named scope for searching with a "LIKE ?" query. A format option can be specified
+ # to change the string used for matching. The default matching string is "%?%".
+ class LikeQueryScope < BaseScope
+ def initialize(model, name, options = {})
+ super
+ @named_scope = options[:named_scope] || "like_#{name}".to_sym
+ @format = options[:format] || "%%%s%%"
+ @model.named_scope @named_scope, lambda { |q| {:conditions => ["#{@name} LIKE ?", @format % q]} }
+ end
+
+ def scope_for(finder, options = {})
+ query = options.delete(@name)
+ query.blank? ? finder : finder.send(@named_scope, query)
+ end
+ end
+
+ SearchScopes.scope_types[:like] = LikeQueryScope
+end
@@ -103,22 +103,23 @@ def ==(other)
end
end
- #class LikeQueryScope < BaseScope
- # def initialize(model, name, options = {})
- # super
- # @named_scope = options[:named_scope] || "like_#{name}".to_sym
- # @model.named_scope @named_scope, lambda { |q| {:conditions => ["#{@name} LIKE ?", "%#{q}%"]} }
- # end
- #
- # def scope_for(finder, options = {})
- # query = options.delete(@name)
- # query.blank? ? finder : finder.send(@named_scope, query)
- # end
- #end
+ class LikeQueryScope < BaseScope
+ def initialize(model, name, options = {})
+ super
+ @named_scope = options[:named_scope] || "like_#{name}".to_sym
+ @format = options[:format] || "%%%s%%"
+ @model.named_scope @named_scope, lambda { |q| {:conditions => ["#{@name} LIKE ?", @format % q]} }
+ end
+
+ def scope_for(finder, options = {})
+ query = options.delete(@name)
+ query.blank? ? finder : finder.send(@named_scope, query)
+ end
+ end
SearchScopes.scope_types.update \
- :reference => ReferenceScope#,
- #:like => LikeQueryScope
+ :reference => ReferenceScope,
+ :like => LikeQueryScope
end
send respond_to?(:require_dependency) ? :require_dependency : :require, 'can_search/date_range_scope'

0 comments on commit 56d0fd2

Please sign in to comment.