Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails - include module into controller, to be used in the view

I'm really new to Rails and I try to setup a module file to be used in the view. So I believe the correct behavior is to define the module as a helper within a controller and voila, it should be working. However, that's not the case 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 like the above and when I call the error_message from new.html.erb it gives me the error: uninitialized constant UsersController::FormManager.

So, first of all, I know that in rails 3 lib is not automatically loaded. Assuming that it is not mandatory to autoload the lib folder, how can I make this work and what am I missing?

BTW, please don't say that this question is duplicate. I'm telling you I've been searching for this crap for almost 2 days.

like image 448
Savas Vedova Avatar asked Jun 15 '12 15:06

Savas Vedova


1 Answers

Your module is not autoloaded (at least not in 3.2.6). You have to load 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 your autoload paths with Rails.application.config.autoload_paths. Maybe it's indeed defined for you?

Now you're sure your module gets loaded, you can check it in rails console by calling

> Functions::FormHelper

Now you can't use that module as a view helper by default. Use #included to define the helper when your module gets included. You achieve "lazy evaluation" this way. I think the problem with your code is that the helper method gets called before the module gets included. (somebody should correct me if I'm wrong)

Here's 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 autoloading. Just use require "functions/form_manager". You define a helper_method for every method. If you wish use all the module methods as helpers use

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

EDIT2:

It appears that you don't need to use self.included. This achieves the same functionality:

class ApplicationController < ActionController::Base

  include Functions::FormManager
  helper_method Functions::FormManager.instance_methods

end
like image 103
shime Avatar answered Nov 20 '22 12:11

shime