107

I would like to use to_dollar method in my model like this:

module JobsHelper      
  def to_dollar(amount)
    if amount < 0
      number_to_currency(amount.abs, :precision => 0, :format => "-%u%n")
    else
      number_to_currency(amount, :precision => 0)
    end
  end      
end

class Job < ActiveRecord::Base
  include JobsHelper
  def details
    return "Only " + to_dollar(part_amount_received) + 
           " out of " + to_dollar(price) + " received."
  end
end

Unfortunately, the number_to_currency method is not recognized here:

undefined method `number_to_currency' for #<Job:0x311eb00>

Any ideas how to make it work?

11 Answers 11

197

I agree with all of you that this could be breaking the MVC pattern but there is always reasons to break a pattern, in my case I needed these currency formatter methods to use them in a template filter (Liquid in my case).

At the end I found out I could access to these currency formatter methods using things like this:

ActionController::Base.helpers.number_to_currency
3
  • 7
    This is good, though there is a slightly cleaner way of doing it. See http://railscasts.com/episodes/132-helpers-outside-views
    – user664833
    Apr 4, 2012 at 18:09
  • 4
    Yay comment track in RailsCasts: In Rails 3 in 2013, using a View helper in a Controller is done like view_context.number_to_currency(amount) Jul 30, 2013 at 8:08
  • 3
    Have you thought about using the "money" gem? As money object provides a format() method, and you can invoke it in the model, controller, or view.
    – Zack Xu
    Aug 8, 2013 at 13:43
111

It’s not available because its use in a model (typically) violates MVC (and it does seem to in your case). You're taking data and manipulating it for presentation. This, by definition, belongs in the view, not the model.

Here are some solutions:

  • Use a presenter or view model object to mediate between the model and view. This almost definitely requires more initial work than other solutions, but is almost always a better design. Using helpers in a presenter/view-model doesn’t violate MVC, as they reside in the view layer, replacing traditional custom Rails helpers and logic-filled views.

  • Explicitly include ActionView::Helpers::NumberHelper in JobsHelper instead of depending on Rails to have magically loaded it for you. This is still not great, as you shouldn’t access a helper from a model.

  • Violate MVC & SRP. See fguillen’s answer for how to do this. I won’t echo it here because I don’t agree with it. Even more so, though, do I disagree with polluting your model with presentation methods as in Sam’s answer.

If you think “but I really need this to write my to_csv & to_pdf methods in my model!”, then your entire premise is wrong—after all, you don’t have a to_html method, do you? And yet your object is very often rendered as HTML. Consider creating a new class for generating your output instead of making your data model know what a CSV is (because it shouldn’t).

As for using helpers for ActiveModel validation errors in the model, well, I’m sorry but ActiveModel/Rails has screwed us all there by forcing error messages to be realized in the data layer, rather than returning the semantic idea of an error to be realized later—sigh. You can get around this, but it basically means not using ActiveModel::Errors anymore. I’ve done it, it works well.

As an aside, here’s a useful way to include helpers in a presenter/view-model without polluting its set of methods (because being able to do e.g. MyPresenterOrViewModel.new.link_to(...) makes no sense):

class MyPresenterOrViewModel
  def some_field
    helper.number_to_currency(amount, :precision => 0)
  end

  private

  def helper
    @helper ||= Class.new do
      include ActionView::Helpers::NumberHelper
    end.new
  end
end
13
  • 5
    I usually follow this rule but break it when I need a view helper to format a validation error message defined in the model.
    – Florent2
    Mar 3, 2011 at 14:58
  • 48
    This is good advice, but it's a bad answer because it does not solve the question.
    – Jaryl
    Jun 29, 2012 at 10:28
  • 22
    There are cases where this is not a great answer, for instance right now where I am buiding a csv report and need to use something like this in a to_csv method in a class that will never see a view. Just sprouting programming ideals is not always helpful.
    – nitecoder
    Jul 30, 2012 at 0:53
  • 1
    Yea, what nitecoder said. I'm running into the same issue. I'm generating PDF reports and simply want to nicely format a phone number.
    – James Adam
    Nov 26, 2012 at 0:09
  • 3
    @maurice It’s a slippery slope from “well just this one thing” to a bloated model. App helpers in Rails are a junk-drawer, presenters/view-models are easier to manage. I don’t see creating the data for a report and generating the (html|pdf|csv|etc.) view of that data as a single responsibility any more than I do for, e.g., a person and an HTML person show page. Jun 12, 2015 at 13:36
92

I know this thread is very old, but someone can look for solution for this problem in Rails 4+. Developers added ActiveSupport::NumberHelper, which can be used without accessing view related modules/classes using:

ActiveSupport::NumberHelper.number_to_currency(amount, precision: 0)
1
  • This approach worked for me when I wanted to experiment with the behavior of number_to_percentage in the Rails console. Thanks! Feb 19, 2019 at 19:40
29

You need to also include the ActionView::Helpers::NumberHelper

class Job < ActiveRecord::Base
  include ActionView::Helpers::NumberHelper
  include JobsHelper
  def details
    return "Only " + to_dollar(part_amount_received) + 
           " out of " + to_dollar(price) + " received."
  end
end
4
  • 2
    Thanks, looks good, but I have to agree with others that say I violate the MVC. I'll put details in the helper. Mar 3, 2011 at 4:53
  • 1
    Helpful if you are like Florent2 and need to put it as part of a validation message. Thanks Sam.
    – RyanJM
    May 18, 2011 at 17:01
  • This worked for me. I don't think it makes sense to always follow MVC (or any principle) if a solution that violates that principle is clearly better than one that adheres to it. Jul 10, 2011 at 3:43
  • 2
    This approach is not recommended. It adds a lot of methods which you don't need, and it clutters up your namespace, it may overwrite some methods, and some helper modules rely on other helper modules (so you may need to include multiple modules), thereby making the issue even worse. For an explanation and better approach, see: http://railscasts.com/episodes/132-helpers-outside-views
    – user664833
    Apr 4, 2012 at 18:06
6

Piggybacking off of @fguillen's response, I wanted to override the number_to_currency method in my ApplicationHelper module so that if the value was 0 or blank that it would output a dash instead.

Here's my code in case you guys would find something like this useful:

module ApplicationHelper
  def number_to_currency(value)
    if value == 0 or value.blank?
      raw "&ndash;"
    else
      ActionController::Base.helpers.number_to_currency(value)
    end
  end
end
4

You can use view_context.number_to_currency directly from you controller or model.

4

You can just include ActiveSupport::NumberHelper module, if you don't need additional features defined by ActionView.

https://github.com/rails/rails/blob/44260581bec06e4ce05f3dd838c8b4736fc7eb1d/actionview/lib/action_view/helpers/number_helper.rb#L383

3

@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
2

It is not a good practice but it works for me!

to import include ActionView::Helpers::NumberHelper in the controller. For example:

class ProveedorController < ApplicationController
    include ActionView::Helpers::NumberHelper
    # layout 'example'

    # GET /proveedores/filtro
    # GET /proveedores/filtro.json
    def filtro
        @proveedores = Proveedor.all

        respond_to do |format|
            format.html # filtro.html.erb
            format.json { render json: @proveedores }
        end
    end

    def valuacion_cartera
        @total_valuacion = 0
        facturas.each { |fac|
            @total_valuacion = @total_valuacion + fac.SumaDeImporte
        }

        @total = number_to_currency(@total_valuacion, :unit => "$ ")

        p '*'*80
        p @total_valuacion
    end
end

Hope it helps you!

2

Really surprised not one person has talked about using a Decorator. Their purpose is to solve the issue you are facing, and more.

https://github.com/drapergem/draper

EDIT: Looks like the accepted answer basically did suggest doing something like this. But yeah, you want to use decorators. Here's a great tutorial series to help you understand more:

https://gorails.com/episodes/decorators-from-scratch?autoplay=1

P.S. - @excid3 I accept free membership months LOL

-5

Helper methods are generally used for View files. It is not a good practice to use these methods in Model class. But if you want to use then Sam's answer is ok. OR I suggest you can write your own custom method.

1
  • 2
    This is not an answer.
    – Bonifacio2
    Jan 19, 2015 at 17:04

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.