Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Outputing value of TrueClass / FalseClass to integer or string/

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?

like image 755
konung Avatar asked Mar 26 '10 16:03

konung


2 Answers

You could create a file such as lib/boolean_ints.rb and monkey-patch a to_i method to TrueClass and FalseClass, as you suggested. Then, in the models or controllers in which you need to use the to_i method, you could just put

require 'boolean_ints'

at the top, and they'd be available for use.

like image 67
mipadi Avatar answered Nov 10 '22 17:11

mipadi


Extend TrueClass and FalseClass with humanize and to_i.

This comes up in most of my projects so I use an initializer (if you're using Rails) that adds these two helpful methods to each class, like so:

config/initializers/true_and_false.rb

class TrueClass
  def humanize
    'Yes'
  end

  def to_i
    1
  end
end

class FalseClass
  def humanize
    'No'
  end

  def to_i
    0
  end
end

Then it makes rendering true very easy for both "human consumption" and "machine consumption":

> true.humanize     #=> Yes
> true.to_i         #=> 1

> false.humanize    #=> No
> false.to_i        #=> 0
like image 31
Joshua Pinter Avatar answered Nov 10 '22 16:11

Joshua Pinter