在Rails应用程序中使用自定义功能 [英] Using custom functions in rails app

查看:69
本文介绍了在Rails应用程序中使用自定义功能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试遵循以下答案中的简短示例,以在rails中使用自定义函数:

I am trying to follow the short example in the following answer on using custom functions in rails:

http://stackoverflow.com/questions/2879679/where-to-put-code-snippets-in-rails

在lib / math.rb中的math.rb中

In math.rb in lib/math.rb

module Math
    class << self
        def cube_it(num)
          num*3
        end
    end
end

在Rails控制台中,我已经尝试过

In rails console I have tried

include Math
Math.cube_it(2)

但是我得到了错误:

NoMethodError: undefined method 'cube_it' for Math:module


推荐答案

在config / application.rb中检查下一行

check config/application.rb for next line

# Custom directories with classes and modules you want to be autoloadable.
config.autoload_paths += %W(#{config.root}/lib)

因此,如果您仍要卸载扩展程序,则可以输入

So if you have still unloadable extension you can type

require 'math'

并重新检查

您可以创建config / initializers / lib.rb

instead of call require, you can create config/initializers/lib.rb

with


Dir [File.join(Rails.root, lib , * .rb)]。each每个{| l |要求l}

Dir[File.join(Rails.root, "lib", "*.rb")].each {|l| require l }

这篇关于在Rails应用程序中使用自定义功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆