views:

386

answers:

1

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, model, 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?

A: 

To answer your question you can probably store the request object in the current thread with:
Thread.current[:request] = request At the time the shortly after the request has been made (before filter?) and then get it out again in the model or controllers or views with Thread.current[:request]

But I would argue this is a bad idea for a multitude of reasons.

There should be a better way accomplish what you are trying to do. What do you mean by internal_request? Why do models need to have access to this kind of information? If there is some code dependent on where a request has originated, that code should pretty much stay in the controllers.

stefan.natchev
Just as a general observation: I have found that if something in rails requires jumping through code-hoops, I am probably approaching it wrong.
stefan.natchev