The following universal_methods.rb
file is placed in the controllers directory to contain methods to share across controllers.
class UniversalMethods
def initialise_municipal(user_params)
user_params = params[:user]
municipal_via_id = user_params[:municipal_id]
[...]
end
end
The UserController method is instantiated and contains a method calling the above:
require_dependency 'universal_methods'
class UsersController < ApplicationController
def admin_create
set_user_login_name
user_params = params[:user]
initialise_municipal(user_params)
[...]
end
I have tested that the application accesses the file (by using just require
it complains of not finding if). However, the method is definitely not accessed:
NoMethodError: undefined method
initialise_municipal' for #UsersController:...`
What is wrong in this syntax / setup ?
CodePudding user response:
To strictly fix your code you need UniversalMethods.new.initialise_municipal(user_params)
instead of just initialise_municipal(user_params)
and there's no need to require the file because everything in /controllers
is autoloaded.
Another approach for this is with Concerns. Create a folder app/controllers/concerns
and put universal_methods.rb
there.
For Rails 6
# app/controllers/concerns/universal_methods.rb
module UniversalMethods
extend ActiveSupport::Concern
included do
def initialise_municipal(user_params)
user_params = params[:user]
municipal_via_id = user_params[:municipal_id]
end
end
end
# app/controllers/users_controller.rb
class UsersController < ApplicationController
include UniversalMethods
def admin_create
set_user_login_name
user_params = params[:user]
initialise_municipal(user_params)
[...]
end
end