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:
- Make a folder RAILS ROOT/lib/core_extensions
- In there, create a file named fixenum_extensions.rb
- Copy/paste the code below into that file.
- In your environment.rb file, put this line:
- And this line:
- And restart your application
RAILS_ROOT = "#{File.dirname(__FILE__)}/.." unless defined?(RAILS_ROOT)require "#{RAILS_ROOT}/lib/core_extensions/fixnum_extensions"###
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 }
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!