Wednesday, March 14, 2007

The Boolean connection

Few people understand the true mentality of dealing with a Boolean variable.
The normal programmer will panic, and immediately attempt to compare it to a Boolean constant.

when using Rails, This is wrong.

When migrating a boolean typed column using Rails, the actual column type created is "tinyint(1)" (a single digit number presentation which means that the actual value being saved is 0's or 1's.
Where is the problem? in Ruby for a change.
In Ruby, everything except nil and false is considered to a true value. In C, Python and many other languages, 0 and possibly other values, such as empty lists, are considered as false.

which brings us to the inevitable conclusion, that simplay comparing boolean values to true or false will not do.

Rails solves this tiny issue for us, for each boolean attribute, Rails implements a "query method" as i prefer to call them. These query methods are simply called by issuing the boolean attribute name with a "?" suffix.

for example, the @mail_message instance object has a is_important boolean attribute, so instead of doing:


@mail_message.is_important == true

or whatever, we can simply ask rails by:

@mail_message.is_important?


beautiful... isn't it?

3 comments:

  1. thanx for your contribution Elad.


    btw, the style for code isn't readable - the font color and the background color are the same.

    looking forward to future articles.

    Jodi

    ReplyDelete
  2. oops, too much beer i guess :)
    fixed.

    and tnx :) there are more to come for sure..

    ReplyDelete
  3. This is one of those things I love about Rails.

    ReplyDelete

Tell me what you think