Autonomous Machine

Interrogation creates boolean accessors from named_scope declarations

This is a little hack I came up with today when I got tired of duplicating logic in scopes and accessor methods. If I define a method in a model like this:

class Submarine < ActiveRecord::Base
  named_scope :on_surface, :conditions => {:location => 'surface'}
  named_scope :submerged, :conditions => {:location => 'under water'}

I think I should be able to interrogate the model to see if it is in these scopes without needing to define Submarine#on_surface? or Submarine#submerged? This is what I want to be able to do:

sub = Submarine.first => #<Submarine id: 1, location: 'surface'>
sub.on_surface? => true
sub.submerged? => false

Interrogation will allow for exactly this. The first version would fire a database query on each call, but I've since added in an attempt at parsing simple conditions against a model's attributes, with a fallback to the database for complicated conditions.

One last thing

The largest problem with this approach is an object's state is not always in sync with the database. I've thought about this a lot, and at this point I think it's best to raise an exception when using these methods on dirty objects. I think handling dirty objects is beyond the scope of this little hack.

The code is on Github.