Rails: how can I access the request object outside of the helper or controller?

In my application_helper.rb file, I have a function like this:

 def internal_request? server_name = request.env['SERVER_NAME'] [plus more code...] end 

This feature is required in controllers, models, and views. So, I put this code in the utility function file in the lib/ directory. However, this did not help: I ​​received request complaints that were not defined.

How can I access the request object in a file in the lib/ directory?

+7
ruby-on-rails request helpers
source share
1 answer

The simplest thing that would seem to work here is to pass the request object to the method.

 def internal_request?(request) server_name = request.env['SERVER_NAME'] [plus more code...] end 

It is assumed that this method is ever called a query, and that you can pass it to a method.

I am trying to think of a scenario where models will need to call this method directly. It seems more likely that you can check if it was an internal_request in your controller (mark it as helper_method in your controller, if you need it in your view), and then tell your model that it was an internal_request.

+2
source share

All Articles