10

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
New Alexandria
  • 6,951
  • 4
  • 57
  • 77

1 Answers1

22

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
Sergio Tulentsev
  • 226,338
  • 43
  • 373
  • 367
  • Do I have to specify `RAKE_ENV` every time I run the command, or can it remember for me? –  Jan 22 '13 at 11:07
  • ENV includes all environment variables known to a new process. So if you put that var into a `.profile` (or whatever init file you use), it will be remembered across system restarts. You can choose any name, by the way, not necessarily RAKE_ENV. Just make sure it's unique enough, so you don't overwrite any other env var. – Sergio Tulentsev Jan 22 '13 at 11:10
  • Do I just create a `.profile` file in my project directory or is this a system wide thing? –  Jan 22 '13 at 11:12
  • @OliverJosephAsh: it's system-dependent. Different systems (and shells) use different files. But this is a bit off-topic here. You should ask that (how to persist env var) on [Super User](http://superuser.com/). – Sergio Tulentsev Jan 22 '13 at 11:15
  • Cheers. http://superuser.com/questions/539913/how-to-persist-ruby-environment-variable –  Jan 22 '13 at 11:19