acts_as_boolean Ruby on Rails plugin

On off switch image

acts_as_boolean is a Ruby on Rails plugin I wrote that treats a column as a boolean, whether it’s a tinyint, integer, float, string, etc. No matter how true and false are stored in the database.

This is useful when you don’t have control over how booleans are stored by different applications. For example: Microsoft Access stores booleans as 0 and -1. Normally -1 in a MySQL database, would be converted, by Rails/ActiveRecord, into a false, rather than true as it should be.

You can use either foo (assuming your column is foo) or foo? methods and they return the same result.

The following are false (lower, upper, or any other case), all else are true:

false, nil, 0, 0.0, '', '0', '0.0', 'f', 'false', 'n', 'no', 'negative', [], {}

You can add to these, for individual columns, using the false_is_also parameter.
Note: if you use the set_false_as parameter, it will automatically be added to the list of falses for this column.

You can specify a specific way a boolean should be stored in the database, when it's assigned, with set_false_as and set_true_as. This, however, will not change how the column is evaluated on read. In other words, if you save a false as ‘nope’, a value of 0 or ‘f’ in the database will still be read as a false. It only affects how it is stored in the database.

Parameters

  • set_false_as – What false value to store in the column on assignment. By default any value will be stored, and converted to true or false when you read the value.
  • set_true_as – What true value to store in the column on assignment. By default any value will be stored, and converted to true or false when you read the value.
  • false_is_also – Additional values to be treated as false

Examples

The most simple example is when you want column foo to return true and false correctly for both foo and foo? methods. To do that, simply add the following to your model:

acts_as_boolean :foo

Some other examples:

class Person < ActiveRecord::Base
  acts_as_boolean :alive, :employee
  acts_as_boolean :vendor, :client, :set_true_as => -1
  acts_as_boolean :foo, :false_is_also => ['nine', 'nada', 9999]
  acts_as_boolean :bar, :set_false_as => 'no', :set_true_as => 'yes', :false_is_also => 'nyet'

  #...
end

Install

For Rails 2.1 and above:

ruby script/plugin install git://github.com/twerth/acts_as_boolean

To upgrade:

ruby script/plugin install git://github.com/twerth/acts_as_boolean.git --force

License

Released under the MIT license

Code Repository

The code repository can be found on github here. Happy coding.

Share:
dzone del.icio.us digg it reddit spurl simpy blinklist furl blogmarks magnolia

  1. john bender November 19, 2008 05:15 

    Nice way to extend Ruby's better handling of boolean + null. I'll give this a try soon in one of my projects.

Leave a new comment:     = Required


(will not be shown)