views:

470

answers:

2

I'd got a model in which attributes are allowed to be null, but when a null attribute is read I'd like to take a special action. In particular, I'd like to throw a certain exception. That is, something like

class MyModel < ActiveRecord::Base

def anAttr
    read_attribute(:anAttr) or raise MyException(:anAttr)
end

end

that's all fine, but it means I have to hand-code the identical custom accessor for each attribute.

I had thought I could override read_attribute, but my overridden read_attribute is never called.

A: 

Not sure why you'd need to do this, but alas:

def get(attr)
  val = self.send(attr)
  raise MyException unless val
  val
end

@object.get(:name)
Matt Darby
A: 

That's funny, we were looking into this same thing today. Check into attribute_method.rb which is where all the Rails logic for the attributes exists. You'll see a define_attribute_methods method which you should be able to override.

In the end, I think we're going to do this in a different way, but it was a helpful exercise.

Seth Ladd