12

I would like to format a number in a controller before inserting it into a string. But the function number_with_delimiter() does not work in a controller. I need the string to send to a javascript plugin.

I could run the code in the view, but I guess that is not the best option.

@mycarousel_itemList = @mycarousel_itemList + "{url: '" + p.photo.url(:thumb) + 
"', price: '" + p.price.to_s + " €'}," 

Is there an alternative function to change the format of p.price?

Michael Torfs
  • 828
  • 2
  • 9
  • 24
  • You can refer to my answer here http://stackoverflow.com/questions/4467697/rails-why-the-number-with-delimiter-method-is-not-recognized-inside-my-model/25979370#25979370 – Le Duc Duy Sep 22 '14 at 17:01

3 Answers3

26

To answer your question directly, include the following in your controller (typically near the top, below the class declaration):

include ActionView::Helpers::NumberHelper

You could also include this module in the model (whatever class p is), and then write a function to return the formatted price.

The best place for code like this, however, is in a helper, not the controller. The helper would be called from the view. Your controller should be as short as possible and not include any view logic at all.

wuputah
  • 11,285
  • 1
  • 43
  • 60
20

Just call the underlying ActiveSupport::NumberHelper method directly:

> ActiveSupport::NumberHelper.number_to_delimited(100000)
=> "100,000"

This avoids including all of the ActionView methods in your object unnecessarily.

fotinakis
  • 7,792
  • 2
  • 26
  • 28
3

Rails controllers have access the same context that the ActionView renderer does using the view_context property without having to mixin multiple view helper modules:

class BaseController < ApplicationController                                                                                                      
  def index
    # Accessing view the context
    logger.info view_context.number_to_currency(34)
  end
end

This has the advantage to having complete access to all view helpers as well as any special configuration you may have setup (i.e., i18n settings).

maniacalrobot
  • 2,413
  • 2
  • 18
  • 20