Number to Currency Inside Models

by Melvin Ram

I was working on something where I needed to use number_to_currency inside a model. I wanted @service.price to use the amount & setup_amount fields to output something like this: “$120.00 setup + $23/month”

This is a problem since number_to_currency is part of the ActionView module and not available inside models. Some say that it violates MVC principles since in a way, you’re messing with view-related code inside a model. That part is up for debate. In anycase, ravocx from the rubyonrails IRC channel put together a small snippet that extends Fixnum so you can call some_number.to_currency on it.

Here’s how it works:

  1. Make a folder RAILS ROOT/lib/core_extensions
  2. In there, create a file named fixenum_extensions.rb
  3. Copy/paste the code below into that file.
  4. In your environment.rb file, put this line:
  5. RAILS_ROOT = "#{File.dirname(__FILE__)}/.." unless defined?(RAILS_ROOT)
  6. And this line:
  7. require "#{RAILS_ROOT}/lib/core_extensions/fixnum_extensions"
  8. And restart your application

###

require 'rubygems'
require 'action_view'

class Fixnum
  def to_currency(options = {})
    ActionView::Base.new.number_to_currency(self, options)
  end
end

###

For my purpose, I used end deciding to leave the code in the helper for now but I may move to this method later.

DISCLAIMER: If you do use this approach, you might consider moving this code into a module and using that module to extend Fixnum.

{ 1 comment… read it below or add one }

Roy van der Meij (ravocx) April 3, 2009 at 9:22 am

Nice write-up!
The require statements could be left out when you put this snippet in rails.
But this will work outside of rails too.

Keep up the good work!

Leave a Comment