Thank you Harvey. I’d come up with something similar:
def fmt_pounds(amt)
number_to_currency(amt, :unit => “£”)
end
Perhaps I should be happy with that, but it seems neater to me to use
the built in helper, and alter the default.
OK - I’ve copied the number_to_currency code from number_helper.rb to
application_helper.rd in my web application. I then edited it so the
code looks like this:
def number_to_currency(number, options = {})
options = options.stringify_keys
precision, unit, separator, delimiter = options.delete(“precision”) { 2
}, options.delete(“unit”) { “£” }, options.delete(“separator”) { “.” },
options.delete(“delimiter”) { “,” }
separator = “” unless precision > 0
begin
parts = number_with_precision(number, precision).split(’.’)
unit + number_with_delimiter(parts[0], delimiter) + separator +
parts[1].to_s
rescue
number
end
end
Now within the application number_to_currency(10.3) produces £10.30.
Which is what I want. Is this good practice? Have I broken anything?
The way I suggested seems to be the cleanest solution to me. I
personally don’t like the idea of copying Rails code into your own
application. I would have thought that it may cause your maintanability
problems in the future. I’m a newbie to Rails myself so there maybe a
neater way to alter the default but I don’t know what it is. Let me
know if you find a better solution.
I personally don’t like the idea of copying Rails code into your own
application.
I agree. I’m sure I can adjust the way the function behaves without
rewriting all the code. In a couple of places “The Programming Ruby
Guide” (http://www.rubycentral.com/book/index.html) discusses changing
or adding functionality for inbuilt methods and classes. However, with
this example I’m not sure how to do that.
I’m sure there is a neater way of doing this.
Thanks again for your help
This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.