Inequal Opportunity
inequal_opportunity exists because this does not work in ActiveRecord:
Doctor.all(:joins => :patients, :conditions => {:patients => ['age > ?', 20]})
You will get an unknown column exception looking for ‘doctors`.`age`. Instead, you need to write:
Doctor.all(:joins => :pateints, :conditions => ['`patients`.`age` > ?', 20])
Putting the string table name in the query annoyed me. On top of that, I always wanted a way to eliminate strings from my named scopes and queries. So now with inequal_opportunity you can write:
Doctor.all(:joins => :patients, :conditions => {:patients => {:age => gt(20)}})
Not only is it prettier (hashed), but ActiveRecord will keep track of table names for you.
ActiveRecord looks for Array and Range types to decide whether to use ‘IN’ or ‘BETWEEN’ instead of the normal ‘=’ as the comparison operator when generating SQL. inequal_opportunity extends that pattern by wrapping the value in a series of ActiveRecord::Inequality::Base classes. Just wrap the value with one of the following helper functions:
gte() => >=
gt() => >
lte() => <=
le() => <
ne() => <>
ne(nil) => IS NOT
and the appropriate SQL will be generated. This works in finds, as shown above, in counts:
People.count(:age => gt(20))
in named scopes:
class People < AR::B
named_scope :underage, :conditions => {:age => lte(18)}
end
in default scopes:
class Feedback < AR::B
default_scope :conditions => {:type => ne('spam')}
end
and pretty much everywhere else I’ve tested manually.
Test coverage is kind of sparse right now, and it’s only been tested on MySQL. But it has been rock solid in every situation I’ve thrown it in, so I figured the best way to improve it was to release the hounds (YOU).
Note that I am not completely satisfied with the way I alias ActiveRecord::Base.expand_range_bind_variables. It smells, but it works. Suggestions welcome.
License
inequal_opportunity is released under the MIT license.
Support
Just email me at [email protected] with questions, bugs, or patches.