Class: ActiveRecord::Extensions::Like
- Inherits:
-
Object
- Object
- ActiveRecord::Extensions::Like
- Defined in:
- lib/ar-extensions/extensions.rb
Overview
ActiveRecord::Extension to translate Hash keys which end in _like
or _contains
with the approriate LIKE keyword used in SQL.
Examples
# the below two examples are equivalent
Model.find :all, :conditions=>{ :name_like => 'John' }
Model.find :all, :conditions=>{ :name_contains => 'John' }
Model.find :all, :conditions=>{ :name_starts_with => 'J' }
Model.find :all, :conditions=>{ :name_ends_with => 'n' }
Constant Summary collapse
- LIKE_RGX =
/(.+)_(like|contains)$/
- STARTS_WITH_RGX =
/(.+)_starts_with$/
- ENDS_WITH_RGX =
/(.+)_ends_with$/
Class Method Summary collapse
Class Method Details
.process(key, val, caller) ⇒ Object
258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 |
# File 'lib/ar-extensions/extensions.rb', line 258 def self.process( key, val, caller ) values = [*val] case key.to_s when LIKE_RGX str = values.collect do |v| "#{caller.quoted_table_name}.#{caller.connection.quote_column_name( $1 )} LIKE " + "#{caller.connection.quote( '%%' + v + '%%', caller.columns_hash[ $1 ] )} " end when STARTS_WITH_RGX str = values.collect do |v| "#{caller.quoted_table_name}.#{caller.connection.quote_column_name( $1 )} LIKE " + "#{caller.connection.quote( v + '%%', caller.columns_hash[ $1 ] )} " end when ENDS_WITH_RGX str = values.collect do |v| "#{caller.quoted_table_name}.#{caller.connection.quote_column_name( $1 )} LIKE " + "#{caller.connection.quote( '%%' + v, caller.columns_hash[ $1 ] )} " end else return nil end str = str.join(' OR ') result_values = [] str.gsub!(/'((%%)?([^\?]*\?[^%]*|[^%]*%[^%]*)(%%)?)'/) do |match| result_values << $2 '?' end result_values = nil if result_values.empty? return Result.new(str , result_values) end |