Rails - include the module in the controller that will be used in the view

I'm really new to Rails, and I'm trying to customize the module file that will be used in the view. Therefore, I believe that the correct behavior is to determine the module as an assistant in the controller and voila, it should work. However, this is not so for me. Here is the structure.

lib functions -- form_manager.rb 

form_manager.rb:

 Module Functions Module FormManager def error_message() ... end end end 

users_controller.rb

 class UsersController < ApplicationController helper FormManager def new ... 

Well, the structure is similar to the one above, and when I call error_message from new.html.erb , it gives me an error: uninitialized constant UsersController::FormManager .

So, first of all, I know that in rails 3 lib does not load automatically. Assuming it is not necessary to automatically download the lib folder, how can I do this work and what am I missing?

By the way, please do not say that this question is repeated. I tell you, I've been looking for this shit for almost two days.

+6
source share
2 answers

Your module does not autoload (at least not in 3.2.6). You must download it explicitly. You can achieve this with the following line of code

  # in application.rb config.autoload_paths += %W(#{config.root}/lib) 

You can check startup paths using Rails.application.config.autoload_paths . Maybe it is really specific to you?

Now you are sure that your module is loaded, you can check it in the rails console by calling

 > Functions::FormHelper 

Now you cannot use this module as a default view helper. Use #included to determine the helper when your module is turned on. Thus, you achieve a "lazy assessment." I think the problem with your code is that the helper method is called before the module is turned on. (someone should correct me if I am wrong)

Here is the code:

 Module Functions Module FormManager def error_message() ... end def self.included m return unless m < ActionController::Base m.helper_method :error_message end end end 

You should also remove the helper line from your controller.

EDIT:

You can achieve this without startup. Just use require "functions/form_manager" . You define helper_method for each method. If you want to use all methods of the module as helpers, use

 def self.included m return unless m < ActionController::Base m.helper_method self.instance_methods end 

EDIT2:

It seems you do not need to use self.included . This provides the same functionality:

 class ApplicationController < ActionController::Base include Functions::FormManager helper_method Functions::FormManager.instance_methods end 
+14
source

You seem to be in the FormManager namespace inside Functions , which means you will call it helper Functions::FormManager

Try

0
source

Source: https://habr.com/ru/post/918201/


All Articles