Dorian
Dorian

Reputation: 2580

How to list all defined environments in a Rails 3 application?

I was wondering if there is a way to list all defined environments in a Rails application.

For instance if an application has 4 defined environments (production, staging, development, test) I would like to have obtain the following array

 ["production", "staging", "development", "test"]

Any ideas? Thanks

Upvotes: 11

Views: 4140

Answers (5)

Jiří Pospíšil
Jiří Pospíšil

Reputation: 14402

I'm not sure if you can get the list of defined environments through some Rails API. Environment files are loaded dynamically based on the current environment. So as already mentioned, you can just glob the config/environments directory for any .rb file.

Dir.glob("./config/environments/*.rb").map { |filename| File.basename(filename, ".rb") }

If you want to get a list of all database environments defined in database.yml, you can get the list from:

ActiveRecord::Base.configurations.to_h.keys

Assuming you are actually using AR.

Upvotes: 17

Yarin
Yarin

Reputation: 183579

Here you go:

environments = Dir.entries(Rails.root.join("config","environments").to_s).grep(/\.rb$/).map { |fname| fname.chomp!(".rb") }

Upvotes: 1

Deepika
Deepika

Reputation: 826

Try this

Env_path = "#{RAILS_ROOT}/config/environments"
all_env = Dir.entries(Env_path) - ['.','..']
environments = []
all_env.each{|env| environments << env.gsub(".rb", '')} 
print environments

Upvotes: 2

Jakobinsky
Jakobinsky

Reputation: 1294

In Rails 3 you can do the following as Rails.root returns a Pathname object

Dir[Rails.root.join('config', 'environments', '*.rb')].map { |fname| File.basename(fname, '.*') }

Upvotes: 1

Valery Kvon
Valery Kvon

Reputation: 4496

Scan config/environments for .rb. As idea.

Upvotes: 0

Related Questions