jd .
jd .

Reputation: 21

How can all ActiveRecord attribute accessors be wrapped

I've 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 thought I could override read_attribute, but my overridden read_attribute is never called.

Upvotes: 2

Views: 1328

Answers (2)

Seth Ladd
Seth Ladd

Reputation: 120579

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.

Upvotes: 1

Matt Darby
Matt Darby

Reputation: 6324

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)

Upvotes: 4

Related Questions