Class: ActiveRecord::Extensions::Comparison

Inherits:
Object
  • Object
show all
Defined in:
lib/ar-extensions/extensions.rb

Overview

ActiveRecord::Extension to translate Hash keys which end in _lt, _lte, _gt, or _gte with the approriate <, <=, >, or >= symbols.

  • _lt - denotes less than

  • _gt - denotes greater than

  • _lte - denotes less than or equal to

  • _gte - denotes greater than or equal to

Examples

Model.find :all, :conditions=>{ 'number_gt'=>100 } 
Model.find :all, :conditions=>{ 'number_lt'=>100 } 
Model.find :all, :conditions=>{ 'number_gte'=>100 } 
Model.find :all, :conditions=>{ 'number_lte'=>100 }

Constant Summary collapse

SUFFIX_MAP =
{ 'eq'=>'=', 'lt'=>'<', 'lte'=>'<=', 'gt'=>'>', 'gte'=>'>=', 'ne'=>'!=', 'not'=>'!=' }
ACCEPTABLE_COMPARISONS =
[ String, Numeric, Time, DateTime, Date ]

Class Method Summary collapse

Class Method Details

.process(key, val, caller) ⇒ Object



211
212
213
# File 'lib/ar-extensions/extensions.rb', line 211

def self.process( key, val, caller )
  process_without_suffix( key, val, caller ) || process_with_suffix( key, val, caller )
end

.process_with_suffix(key, val, caller) ⇒ Object



225
226
227
228
229
230
231
232
233
234
235
236
237
238
# File 'lib/ar-extensions/extensions.rb', line 225

def self.process_with_suffix( key, val, caller ) 
  return nil unless ACCEPTABLE_COMPARISONS.find{ |klass| val.is_a?(klass) }
  SUFFIX_MAP.each_pair do |k,v|
    match_data = key.to_s.match( /(.+)_#{k}$/ )
    if match_data
      fieldname = match_data.captures[0]
      return nil unless caller.columns_hash.has_key?( fieldname )
      str = "#{caller.quoted_table_name}.#{caller.connection.quote_column_name( fieldname )} " +
        "#{v} #{caller.connection.quote( val, caller.columns_hash[ fieldname ] )} "
      return Result.new( str, nil )
    end
  end
  nil
end

.process_without_suffix(key, val, caller) ⇒ Object



215
216
217
218
219
220
221
222
223
# File 'lib/ar-extensions/extensions.rb', line 215

def self.process_without_suffix( key, val, caller )
  return nil unless caller.columns_hash.has_key?( key )
  if val.nil?
    str = "#{caller.quoted_table_name}.#{caller.connection.quote_column_name( key )} is ?"
  else
    str = "#{caller.quoted_table_name}.#{caller.connection.quote_column_name( key )}=?" 
  end
  Result.new( str, val )
end