comfort zones are for sleeping

Thursday, September 20, 2007

Task A: Mea Culpa

OK, so I got some stuff wrong. Sue me. The point of this blog is to show that a .NET programmer can learn the RoR way of creating web apps. That means I'm learning; that does NOT mean I already know this stuff.

I had some questions about my Product class, specifically these lines:

  validates_presence_of :title, :description, :image_url
validates_numericality_of :price
validates_uniqueness_of :title
validates_format_of :image_url,
:with => %r{\.(gifjpgpng)$}i,
:message => "must be a URL for a GIF, JPG, or PNG image"
Apparently Ruby likes to call these declarations, and they are executed when the class is instantiated. I'm still guessing about some things: in my head, I'm assuming that these are instance properties whose values get set by the constructor. Then when the validate() method gets called as the object is saved, it checks the value of these properties as part of the base validate() logic. Am I anywhere near right on this?

1 comment:

Mason Browne said...

If you poke around a bit, you'll find that these are just methods from the superclass (or, in the case of "acts_as_*", methods that are imported as a mixin). They are indeed executed at runtime, after instantiation, and in some cases add methods to your controller/model/what-have-you.

In the case of validators, they are ran at runtime, and add the information specified to the validation stack, which is then called before save.

If you'd like a more visible example of this, install a plugin (for example, file_column, which aids in uploaded files), and poke around at the code in the vendor directory. You'll see (in the case of file column) that it's a module that's included when the app starts, and by actually calling the "file_column" method as a statement, it binds a bunch of additional methods to your object (using define_method(&block)).

Oh Ruby. You are so much fun.