在rails app中使用自定义function
我试图按照以下答案中的简短示例来使用rails中的自定义函数:
http://stackoverflow.com/questions/2879679/where-to-put-code-snippets-in-rails
在lib / math.rb中的math.rb中
module Math class << self def cube_it(num) num*3 end end end
在rails控制台中我试过了
include Math Math.cube_it(2)
但我得到错误:
NoMethodError: undefined method 'cube_it' for Math:module
检查config / application.rb是否有下一行
# Custom directories with classes and modules you want to be autoloadable. config.autoload_paths += %W(#{config.root}/lib)
因此,如果您仍有可卸载的扩展名,则可以输入
require 'math'
并重新检查
而不是调用require,您可以创建config / initializers / lib.rb
同
Dir [File.join(Rails.root,“lib”,“* .rb”)]。每个{| l | 要求l}