Attr_boolean, a good idea?

Hello all,

I’ve recently been working with a model with a lot of boolean
attributes and I decided that it’s worth trying to implement a
attr_boolean function to cut down on the work. Something like

class User < ActiveRecord::Base
attr_boolean :contact_by_email, :display_real_name, :administrator
end

which would replace the hand written

class User < ActiveRecord::Base

def contact_by_email?
	self.contact_by_email == 1
     end

def display_real_name?
	self.contact_by_email == 1
     end

def administrator?
	self.contact_by_email == 1
     end

end

My questions are :

  1. Does this facility already exist and I’ve just missed it?
  2. Is it a good idea\worth the effort?
  3. What’s the preferred way of representing a boolean in a database
    agnostic way? I usually just use a not null int field where !0 is true.

Many thanks,
Gavin

Oops, in the hand-written example it should not, of course, read
[ self.contact_by_email ==1 ] inside every definition.

G

On 6/22/06, Gavin M. [email protected] wrote:

  1. Does this facility already exist and I’ve just missed it?

Yes. You can use model.attribute? to query an attribute. That
functionality is built in and should do what you want.

  1. Is it a good idea\worth the effort?

Unlikely, since Rails can already do this.

  1. What’s the preferred way of representing a boolean in a database
    agnostic way? I usually just use a not null int field where !0 is true.

I think that’s pretty standard. When you define your tables in a
migration you simply define them as :boolean and it will map to the
appropriate data type, usually just a integer.

-Jonathan.

Ah, I thought it seemed a bit to obvious to not have been
implemented! I’m not sure how I missed it.

Many thanks,
Gavin

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs