Feb 28

Override helpers in Rails

Sooner or later need to override some built in Rails helpers would occur. For example, I like to use number_to_currency helper to format prices in my application, but I want all prices to be formated in euros instead of dollars.

Worth noting is that you cannot simple redefine number_to_currency in application_helper.rb what would be the first thing on my mind to do. You can not redefine original helper method in ActionView::Base class as well. That is because helpers are included as mixin and methods from module are made available to class that includes the module, they are not copied, so if module methods are changed later so are the modules method in a class. Original helper method should be replaced in module where it comes from and in case of currencies this is ActionView::Helpers::NumberHelper.

Here is example that replaces original number_to_currency method and set default currency to Euro:

module ActionView
  module Helpers
    module NumberHelper
      def number_to_currency_with_euro(number, options = {})
        defaults = {:unit => ''}
        s = number_to_currency_without_euro(number, defaults.merge(options))
        s << ' &euro;' unless options[:unit]
      alias_method_chain :number_to_currency, :euro