views:

113

answers:

2

Hello.

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?

+1  A: 

You could just monkeypatch the TrueClass and FalseClass in your app, near that particular model: any implementation of to_i on true and false are likely to be the same.

irb(main):004:0> true.to_i
NoMethodError: undefined method `to_i' for true:TrueClass
        from (irb):4
irb(main):005:0> class TrueClass
irb(main):006:1>  def to_i
irb(main):007:2>   1
irb(main):008:2>  end
irb(main):009:1> end
=> nil
irb(main):010:0>
irb(main):011:0* true.to_i
=> 1

But to avoid monkeypatching, is there any reason you couldn't just use the ternary operator? If that's still not DRY enough for you, wrap it up in a method.

irb(main):012:0> true ? 1 : 0
=> 1
irb(main):013:0> false ? 1 : 0
=> 0

Of course, that works with non-boolean variables as well:

irb(main):019:0* 1234 ? 1 : 0
=> 1
irb(main):020:0> nil ? 1 : 0
=> 0
Mark Rushakoff
@Mark - I already did this - but I asked if there is a way to do this "short of adding to_i method to TrueClass/FalseClass." or using if else statements - which is what ternary operator really is, I was trying to see if there is another way to do this that I don't know off. However it doesn't make sense to me thou - that False.to_s works and produces "false" string, but to_i is not implemented in the core class. Thank you thou for your response.
Nick Gorbikoff
+2  A: 

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.

mipadi
@mipadi - related to this, is there a specific convention on how things should be structured/named/layed out in lib?
Nick Gorbikoff
I don't know of a convention for `lib` per se. I usually just try to name things as clearly and succinctly as possible.
mipadi