The blog of Rahoul Baruah from 3hv Ltd

What's going on?

My name is Rahoul Baruah (aka Baz) and I'm a software developer in Leeds (England).

This is a log of things I've discovered while writing software in Ruby on Rails. In other words, geek stuff.

However, I've decided to put this blog on ice - I would ask you to check out my business blog here (or subscribe here).

31 January, 2007

Stupid mistakes and helpful hints

I'm English. Which means I spell English and not Yank.

This also means that I waste hours of my precious time wondering why my constructor is not working when in fact I have written


def initialise(params = nil)
super
do_whatever
end


Spot the error?

When using Single Table Inheritance and overriding validate, don't forget to call super in your descendant class, otherwise validate doesn't get called in your super-class. Obvious but it has caught me out.

And lastly, if you are using attr_accessor to create "temporary" attributes and you want to use validations on them, you will find you get a "NoMethodError: undefined method `my_attribute_before_type_cast' for Whatever". However, the following method (adapted from Rails Recipes - recipe 64) will fix it:


def method_missing(symbol, *params)
if (symbol.to_s =~ /^(.*)_before_type_cast$/)
send $1
else
super
end
end


Basically, any method call ending in "_before_type_cast" will be re-sent without the suffix - so calling your temporary accessor itself.

Incidentally, I can't get Recipe 64 to work with Rails 1.1.6 (not tried with Rails 1.2.1), which is why I came up with the Pseudo-Model trick.

3 comments:

David said...

Actually the error I spotted was the misspelling of initialiZe ;)

Baz said...

Aye ... initialize is American, initialise is English ...

Baz said...

Just noticed I used the English spelling all the way through my "default values" (http://made-of-stone.blogspot.com/2007/01/default-values-in-your-models.html) article.

eXTReMe Tracker