简体   繁体   中英

Rails - How to use a method from a controller in application.rb?

I have a simple method in the ApplicationController that makes a call to database and load some data. I would need to run it in application.rb , like this:

MY_CONST = method_in_application_controller

But I get this error:

<top (required)>': undefined local variable or method `method_in_application_controller' for main:Object (NameError)

How to load the data in from database in application.rb file?

Thank you.

Really, you shouldn't. The better approach would be to refactor the controller method into somewhere globally accessible, such as a file in the config/initializers file or in application.rb itself. Then call it from the controller. The reason being that controller methods have access to special variables such as request and params which won't be available elsewhere. So it's one of those aspects of Rails development which can be considered part of the framework's design. It's easier to learn how to do things the right way.


This being said, it is possible.

Say I have a route in PagesController called root . It's easy to initialize the controller:

controller = PagesController.new

but running controller.root raises an error:

NoMethodError: undefined method `parameters' for nil:NilClass

Some context is required to explain why this error was raised. My controller has a secure_params method which is called whenever any route is run. This methods expects a params object to be defined in the controller. I also have a before_action in my controller which references session . Both these objects are defined on the request object, which I can "mock" like so:

class FakeRequest
  def parameters
    {}
  end 
  def session
    {}
  end 
end

which can be used like this:

controller = PagesController.new
controller.request = FakeRequest.new
controller.root

This will run the controller action, however the fake request object may need to be altered depending on what your controllers require to function correctly.

If you're adamant about sharing controller methods throughout your app, it's probably easier to use class methods. This removes the necessity to construct a fake request and instantiate the controller.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM