Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails: how can I access the request object outside a 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 function is needed in controllers, models, and views. So, I put this code in a utility function file in the lib/ directory. However, this did not work: I got complaints about request not being defined.

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

like image 373
rlandster Avatar asked Apr 05 '10 03:04

rlandster


1 Answers

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

The assumption is when ever this method is being called a request has been made, and that you can pass it to the method.

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

like image 155
ToreyHeinz Avatar answered Sep 16 '22 12:09

ToreyHeinz