Pablo Fernandez
Pablo Fernandez

Reputation: 287530

Can a piece of code know whether it's running in the context of a Rails request or not?

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)?

Upvotes: 1

Views: 118

Answers (1)

Casual Coder
Casual Coder

Reputation: 1492

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.

Upvotes: 2

Related Questions