Getting Ruby environment variables from Rake

user1082754 picture user1082754 · Jan 22, 2013 · Viewed 24.8k times · Source

I have a Rakefile which has tasks for deploying or building an application. This Rakefile is used in both production and development.

I would like the build task to know what the environment is. Can this be done without passing a parameter to the task when I run it? Can it be done with environment variables?

When in development, I need the task to look like this:

task :build => :clean do
  compass compile -e development
  jekyll
end

And in production, like this:

task :build => :clean do
  compass compile -e production
  jekyll
end

Answer

Sergio Tulentsev picture Sergio Tulentsev · Jan 22, 2013

Yes, you can use environment variables. Here's skeleton implementation:

task :build do |t, args|
  puts "Current env is #{ENV['RAKE_ENV']}"
end

Usage:

% rake build
Current env is 

% RAKE_ENV=development rake build
Current env is development