I’m using mod_rails with capistrano and multi-stage (qa, staging, production), and wrote this workaround so that the RAILS_ENV could be set correctly in each stage. Mod_rails sets RAILS_ENV once in the global server conf file, but I needed it set once for each environment: qa, staging, and production. I tried setting ENV['RAILS_ENV] in each file under config/deploy/ but the setting was not picked up.
Solution – write the correct value into config/environment.rb’s ENV[''RAILS_ENV] while deploying.
So here is my 3 step fix -
Step 1.
I created a new file
lib/set_mod_rails_env.rb
# sets ENV['rails_env'] for mod_rails
# <a href="http://www.megasolutions.net/ruby/search-a-file-and-replace-text-50116.aspx" target="_blank">http://www.megasolutions.net/ruby/search-a-file-and-replace-text-50116.aspx</a>
# Robert Evans'
def ChangeOnFile(file, regex_to_find, text_to_put_in_place)
text = File.read file
File.open(file, 'w+'){|f| f << text.gsub(regex_to_find,
text_to_put_in_place)}
end
ChangeOnFile("#{ARGV[0]}/config/environment.rb", /#mod_rails_env_here/, "ENV['RAILS_ENV']='#{ARGV[1]}'")
Step 2.
Add the following code to config/deploy.rb
namespace :deploy do
desc "set ENV['RAILS_ENV'] for mod_rails"
task :before_restart do
run "ruby #{current_release}/lib/set_mod_rails_env.rb #{current_release} #{stage}"
end
end
Step 3.
Add the following code to config/environment.rb
# deploy.rb will swap this out for the appropriate rails_env.
# mod_rails apparently need this var in this file (not ./environments/qa.rb)
# do not change the following line. Ruby regexp looks for it.
#mod_rails_env_here
That’s it. Let me know if you know of an easier way.