Using custom functions in rails app

2019-07-19 00:28发布

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

In math.rb in lib/math.rb

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

In rails console I have tried

include Math
Math.cube_it(2)

But I get the error:

NoMethodError: undefined method 'cube_it' for Math:module

1条回答
孤傲高冷的网名
2楼-- · 2019-07-19 00:41

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'

and recheck

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

with

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

查看更多
登录 后发表回答