Converting TrueClass / FalseClass to integer.


I'm trying to figure out if there is an easy way to do the following
short of adding to_i method to TrueClass/FalseClass.

Here is a dilemma:
I have a boolean field in my rails app - that is obviously stored as
Tinyint in mysql. However - I need to generate xml based of the data in
mysql and send it to customer - there SOAP service requires the field
in question to have 0 or 1 as the value of this field. So at the time of
the xml generation I need to convert my False to 0 and my True to 1 (
which is how they are stored in the DB). Since True & False lack to_i
method I could write some if statement that generate either 1 or 0
depending on true/false state. However I have about 10 of these
indicators and creating and if/else for each is not very DRY. So what
you recommend I do?

Or I could add a to_i method to the True / False class. But I'm not
sure where should I scope it in my rails app? Just inside this
particular model or somewhere else?

Hi Nick,

That’s a good question :slight_smile:
I think a DRY way could be doing it like this:

module BooleanToInteger
def to_i
self ? 1 : 0

[TrueClass, FalseClass].each { |c| c.send :include, BooleanToInteger }

Hope this helps.