1

I want to print numbers in my rails application with commas. As per the answer here, I could wrap every single number I print with

number_with_delimiter(@number, :delimiter => ',')

However, I don't want to go into my views and apply this manually. I'd much rather override the way integers are printed.

In java/jsp, anything inside a <%= %> tag gets a toString() call to evaluate what is printed on the page, so I figured that overriding the to_s method for the Integer class would do:

class Integer
  def to_s
    number_with_delimiter(self, :delimiter => ',')
  end
end

Unfortunately, this doesn't work in that the numbers printed using the <%=%> tag don't appear with commas. (No errors are raised.)

How do I get this right? Does the <%=%> block not automagically call a to_s method on the given object? How does it evaluate what to print?

Community
  • 1
  • 1

1 Answers1

0

You're monkey patching the wrong thing, you want to patch Fixnum. For example:

>> class Fixnum
>>   def to_s
>>     'pancakes'
>>     end
>>   end
=> nil
>> 1.to_s
=> "pancakes"

and for ERB:

>> ERB.new('<%= 11 %>').result
=> "pancakes"

That said, your shortcut (like most shortcuts) will probably end up causing you various new and interesting problems elsewhere. You will end up sending '1,000' to something (such as a database or client-side JavaScript or ...) that expects '1000' and you'll get a confusing hissy fit for your efforts. You'll also have to worry about the other numeric classes such as Float and Bignum.

Fix your views, don't kludge around your own laziness.

mu is too short
  • 426,620
  • 70
  • 833
  • 800
  • I'd expect there's a class that runs/evaluates ERB files. Is there a way to monkey patch Fixnum in just that context? –  Oct 25 '12 at 03:41
  • @bdares: You might be able to patch and unpatch around the ERB but fixing your views will be easier, faster, and less error prone. Doing it the right way is often the fastest solution. – mu is too short Oct 25 '12 at 03:43