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 << ' €' unless options[:unit]
end
alias_method_chain :number_to_currency, :euro
end
end
end
I am Bojan Mihelac and this blog is dedicated to share code, thoughts, tools and advices I came up with while working in
9 comments
I’m a newly wed and we together with my spouse decided to start building good credit as we started a family of our own, as in future we’ll have buy a house and cars and many other things. I wanted a credit card for both of us, so that we could use it together and accumulate credit rating. Happily, I found a card for spouses at
barclays bank balance transfers with 12 months interest free with no credit fee charge
You can’t always have cash to pay for things you need to obtain immediately. For such occasions banks offer credit cards which differ in purpose and features like interest rates, rewards, fees. But you need to build good credit history to be able to use all the opportunities credit cards give. At
o percent interest discover card
Speak your mind: