I would like to use to_dollar
method in my model like this:
module JobsHelper
def to_dollar(amount)
if amount < 0
number_to_cur
@fguillen's way is good, though here's a slightly cleaner approach, particular given that the question makes two references to to_dollar
. I'll first demonstrate using Ryan Bates' code (http://railscasts.com/episodes/132-helpers-outside-views).
def description
"This category has #{helpers.pluralize(products.count, 'product')}."
end
def helpers
ActionController::Base.helpers
end
Notice the call helpers.pluralize
. This is possible due to the method definition (def helpers
), which simply returns ActionController::Base.helpers
. Therefore helpers.pluralize
is short for ActionController::Base.helpers.pluralize
. Now you can use helpers.pluralize
multiple times, without repeating the long module paths.
So I suppose the answer to this particular question could be:
class Job < ActiveRecord::Base
include JobsHelper
def details
return "Only " + helpers.to_dollar(part_amount_received) +
" out of " + helpers.to_dollar(price) + " received."
end
def helpers
ActionView::Helpers::NumberHelper
end
end