Thursday, November 19, 2009

Notion of Self

I was on my merry way through the Agile Development with Rails book, following the example... then I hit a snag.

The goal of Chapter 11 is to create a User model object with an encrypted password, and the means to authenticate users.

The functional objective was clear enough. The User class featured a special password= assignment operator, designed to set accept a plain text password, and behind the scenes convert and save as an encrypted hash.

Also the User class features a 'static-like' method that authenticates a user by name/password.

The implementation was not familiar to my novice ruby eye. It had strange 'self' keywords in curious spots. I initially thought it must be like 'this' in Javascript, but it was used in different situations that I didn't understand.

These were:

A) In private methods.

B) In method declarations, which seemed to function like Java static methods.

The book did not elaborate beyond stating "Without the self, Ruby would have thought we were assigning to a local variable, and our code would have no effect."

Now, I don't fault the authors for my confusion. This is a book on Rails, not a Ruby primer. Rather than gloss over this point, I decided to search for details on 'self'.

The best explanation I found for the self keyword, elaborated on how ruby invokes a method call on an object:

"Method calling" in Ruby is accomplished through a message-sending mechanism. So


some_object.some_method(args)

is a shorthand for


some_object.send(:some_method, args)

Within a method, 'self' refers to the object that has been 'sent' to the method. So it is somewhat like the this object in Javascript!

So... a private methods in a class like:


def create_new_salt
self.salt = self.object_id.to_s + rand.to_s
end

A public instance-level method often makes use of an internal, private method. By referring to self in the private method, it can alter the calling object without an explicit reference.

Now not exactly intuitive from that definition, is the following method declaration:


def self.method(var)
...
end

This seems strange at first. But think about it this way: the methods marked with self can only be invoked by the owning object instance. Its like a static method in that way.

No comments:

Post a Comment