Class ActiveRecord::Extensions::RangeExt
In: lib/ar-extensions/extensions.rb
Parent: Object

ActiveRecord::Extension to translate a ruby Range object into SQL‘s BETWEEN … AND … or NOT BETWEEN … AND … . This works on Ranges of Numbers, Dates, Times, etc.

Examples

 # the following two statements are identical because of how Ranges treat .. and ...
 Model.find :all, :conditions=>{ :id => ( 1 .. 2 ) }
 Model.find :all, :conditions=>{ :id => ( 1 ... 2 ) }

 # the following four statements are identical, this finds NOT BETWEEN matches
 Model.find :all, :conditions=>{ :id_ne => ( 4 .. 6 ) }
 Model.find :all, :conditions=>{ :id_not => ( 4 .. 6 ) }
 Model.find :all, :conditions=>{ :id_not_in => ( 4 ..6 ) }
 Model.find :all, :conditions=>{ :id_not_between => ( 4 .. 6 ) }

 # a little more creative, working with date ranges
 Model.find :all, :conditions=>{ :created_on => (Date.now-30 .. Date.now) }

Methods

process  

Constants

NOT_IN_RGX = /^(.+)_(ne|not|not_in|not_between)$/

Public Class methods

[Source]

     # File lib/ar-extensions/extensions.rb, line 310
310:     def self.process( key, val, caller )
311:       if val.is_a?( Range )
312:         match_data = key.to_s.match( NOT_IN_RGX )
313:         key = match_data.captures[0] if match_data
314:         fieldname = caller.connection.quote_column_name( key )
315:         min = caller.connection.quote( val.first, caller.columns_hash[ key ] )
316:         max = caller.connection.quote( val.last, caller.columns_hash[ key ] )
317:         str = "#{caller.table_name}.#{fieldname} #{match_data ? 'NOT ' : '' } BETWEEN #{min} AND #{max}"
318:         return Result.new( str, nil )
319:       end
320:       nil      
321:     end

[Validate]