Getting Ruby environment variables from Rake
Asked Answered
E

1

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
Electuary answered 22/1, 2013 at 11:2 Comment(2)
Yes, rake tasks should have access to ENV.Springtail
I have never used ENV, so if someone could kindly demonstrate how I would set the variable (and get it). I'm a ruby n00b.Electuary
S
23

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
Springtail answered 22/1, 2013 at 11:6 Comment(5)
Do I have to specify RAKE_ENV every time I run the command, or can it remember for me?Electuary
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.Springtail
Do I just create a .profile file in my project directory or is this a system wide thing?Electuary
@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.Springtail
Cheers. superuser.com/questions/539913/…Electuary

© 2022 - 2024 — McMap. All rights reserved.