How to use the “number_to_currency” helper method in the model rather than view?

后端 未结 11 1533
有刺的猬
有刺的猬 2021-01-30 03:59

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         


        
11条回答
  •  旧巷少年郎
    2021-01-30 04:29

    @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
    

提交回复
热议问题