开发者

Undefined Method errors in rake tasks and model methods

开发者 https://www.devze.com 2023-03-27 14:01 出处:网络
I\'m trying to re开发者_C百科turn a sum using number_to_currency, but whenever I try to use this method inside a rake task or model class instance, I get NoMethodError: undefined method \'number_to_cu

I'm trying to re开发者_C百科turn a sum using number_to_currency, but whenever I try to use this method inside a rake task or model class instance, I get NoMethodError: undefined method 'number_to_currency' for main:Object

Happens in console too. Any suggestions on why I can't use basic methods inside rake tasks or models?


number_to_currency is a view helper so it is generally only available within views. You could do this:

include ActionView::Helpers::NumberHelper

inside a class if you need to use it somewhere else. Think twice about your design though, using a view helper while messing around in the console is fine but you usually want to push your formatting out to the edges (i.e. views).


Here’s how it works:

Make a folder RAILS ROOT/lib/core_extensions In there, create a file named fixenum_extensions.rb Copy/paste the code below into that file. In your environment.rb file, put this line:

RAILS_ROOT = "#{File.dirname(__FILE__)}/.." unless defined?(RAILS_ROOT)

And this line:

require "#{RAILS_ROOT}/lib/core_extensions/fixnum_extensions"

And restart your application

###

require 'rubygems'
require 'action_view'

class Fixnum
  def to_currency(options = {})
    ActionView::Base.new.number_to_currency(self, options)
  end
end

###
0

精彩评论

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