Michael Torfs
Michael Torfs

Reputation: 848

How to format a number in a ruby on rails controller, number_with_delimiter works only in views

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?

Upvotes: 14

Views: 14097

Answers (3)

fotinakis
fotinakis

Reputation: 8202

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.

Upvotes: 20

maniacalrobot
maniacalrobot

Reputation: 2463

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).

Upvotes: 4

wuputah
wuputah

Reputation: 11395

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.

Upvotes: 29

Related Questions