开发者

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

开发者 https://www.devze.com 2023-01-14 13:57 出处:网络
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 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_item开发者_StackOverflow社区List = @mycarousel_itemList + "{url: '" + p.photo.url(:thumb) + 
"', price: '" + p.price.to_s + " €'}," 

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


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.


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.


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

0

精彩评论

暂无评论...
验证码 换一张
取 消