| Class | ActiveRecord::Extensions::Like |
| In: |
lib/ar-extensions/extensions.rb
|
| Parent: | Object |
ActiveRecord::Extension to translate Hash keys which end in _like or _contains with the approriate LIKE keyword used in SQL.
# 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' }
| LIKE_RGX | = | /(.+)_(like|contains)$/ |
| STARTS_WITH_RGX | = | /(.+)_starts_with$/ |
| ENDS_WITH_RGX | = | /(.+)_ends_with$/ |
# File lib/ar-extensions/extensions.rb, line 258
258: def self.process( key, val, caller )
259: values = [*val]
260: case key.to_s
261: when LIKE_RGX
262: str = values.collect do |v|
263: "#{caller.table_name}.#{caller.connection.quote_column_name( $1 )} LIKE " +
264: "#{caller.connection.quote( '%%' + v + '%%', caller.columns_hash[ $1 ] )} "
265: end
266: when STARTS_WITH_RGX
267: str = values.collect do |v|
268: "#{caller.table_name}.#{caller.connection.quote_column_name( $1 )} LIKE " +
269: "#{caller.connection.quote( v + '%%', caller.columns_hash[ $1 ] )} "
270: end
271: when ENDS_WITH_RGX
272: str = values.collect do |v|
273: "#{caller.table_name}.#{caller.connection.quote_column_name( $1 )} LIKE " +
274: "#{caller.connection.quote( '%%' + v, caller.columns_hash[ $1 ] )} "
275: end
276: else
277: return nil
278: end
279:
280: str = str.join(' OR ')
281: result_values = []
282: str.gsub!(/'((%%)?([^\?]*\?[^%]*|[^%]*%[^%]*)(%%)?)'/) do |match|
283: result_values << $2
284: '?'
285: end
286: return Result.new(str , result_values)
287: end