1

Is it possible for a piece of Ruby code to know whether it's being run in the context of a Ruby on Rails request or not (for example, as a background job or a rake task)?

2
  • Why not pass this information directly? Commented Feb 20, 2014 at 16:56
  • @MichaelSzyndel because I would have to pass down this information down a lot of methods and it would be rather ugly. Commented Feb 24, 2014 at 5:50

1 Answer 1

2

You can try to distinguish if something is executed in rake task by the value or presence of special global variables:

task :tryout do if File.basename($0) == 'rake' puts 'It is a rake task.' end end 

In previous snippet one relies on the $0 path to executable ending with rake. In previous Rails versions there was a $rails_rake_task variable, but in my current env it was not defined ( I've tried that on Rails 4).

In Rails controller, you can check if there was a request from the user with $CGI_ENV global variable or ActionDispach::Request request object.

Sign up to request clarification or add additional context in comments.

2 Comments

Checking for a rake task wouldn't work for me as the code can be run in a variety of environments and my problem is doing something different (faster) when it's in a Rails request.
It is just an example of using already defined global variables for your purpose. What do you mean by 'doing something faster'? Checking already defined global variable in memory isn't fast enough?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.