Hi, this blog is no longer maintained, my new blog is here

Ruby On Rails and a Conning Israeli entrepreneur

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:

  Anonymous

March 14, 2007 at 12:20 PM

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

  Elad Meidar

March 14, 2007 at 12:23 PM

oops, too much beer i guess :)
fixed.

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

  Anonymous

March 14, 2007 at 2:37 PM

This is one of those things I love about Rails.


The Web Ask eizesus.com

Subscribe

    follow me on Twitter

    Twiters Around

    About Me

    My photo
    I am a web developer for more than 9 years, managed, cried, coded, designed and made money in this industry. now trying to do it again.

    Labels