Thursday, May 24, 2012

Rails NoMethodError on calling Module

So I had to create a module and call one of the function from a controller.

After looking on Google I could find this post on RailsForum.
Basically, you have to do that:
in lib/something/task.rb
module Task
  def my_method
    "hello there"
In the application controller
class EnrolmentController < ApplicationController
  include Task

  def index
Please note the difference, my module is in "lib/something/Task.rb".  The file is not at the root of lib.

Why I still have "NoMethodError"?

Pretty easy, you have 2 steps to do. First you need to add this in config/application.rb
config.autoload_paths += Dir["#{config.root}/lib/**/"]

But if you still try it, it's not working... Well, in fact you have to restart your server! When you add a directory and files in config folder, you have to restart your server (same for the translation file)
And that's it!

No comments: