Search code examples
ruby-on-railsruby-on-rails-4autoloadeager-loading

Undefined method error for including a module in a controller action in Rails 4


At the end of the accepted answer to this question is this statement.

...in every rails app, all directories under app/ are automatically in both autoload_paths and eager_load_paths, meaning that adding a directory there requires no further actions.

I added an autoload folder in my app folder. In it I have a file named assemble_best.rb with the following contents to test it out:

# app/autoload/assemble_best.rb
module AssembleBest
  def best_assembly(user_id,incl_confirms)
    p "****"
    p 'yo! it worked!'
  end
end

In my controller I have:

best_assembly(current_user.id, true)

The error I get is:

undefined method `best_assembly'

In a variety of syntax for each I've tried adding before_action and require statements. I've also attempted putting the folder in the lib folder and adding auto load referencing the file in my application.rb. Nothing I've tried works. Also tried creating an initializer. I know I could add it to my application controller, but it is already huge. This is the first step toward reducing the size of that controller.

Thanks for your help.


Solution

  • You didn't include that module anywhere. Hence the error. Do this in your controller:

    class MyController < ApplicationController
      include AssembleBest