Environtment variable not show in rails c

593 views Asked by At

I wanna ask about ruby on rails, Environment variable can be set using application.yml

I have a code like this in application.yml

defaults: &defaults
  STORE_URL: https://localhost:3000/

development:
  <<: *defaults

test:
  <<: *defaults

production:
  <<: *defaults

and also set the configuration on application.rb

Bundler.require(*Rails.groups)

if File.exists?(File.expand_path('../application.yml', __FILE__))
  config = YAML.load(File.read(File.expand_path('../application.yml', __FILE__)))
  config.merge! config.fetch(Rails.env, {})
  config.each do |key, value|
    ENV[key] ||= value.to_s unless value.kind_of? Hash
  end
end

and add this code to .gitignore

config/appication.yml
.project

the output should be like this when i test it on terminal,

[1] pry(main)> ENV
=> {"Test1"=>"Tester1",
    "Test2"=>"Tester2",
    "Test3"=>"Tester3"}

It should just add some a Key and Value when i run rails c development

In Rails 3.0.20 and Ruby 1.9.3p545 it work so simple when i tested it by type or adding new Key and Value on application.yml .but, on Rails 4.1.5 and Ruby 2.0.0p541 it wont goes like that

Full Application.rb

require File.expand_path('../boot', __FILE__)

require 'rails/all'

# Require the gems listed in Gemfile, including any gems
# you've limited to :test, :development, or :production.
Bundler.require(*Rails.groups)

if File.exists?(File.expand_path('../application.yml', __FILE__))
  config = YAML.load(File.read(File.expand_path('../application.yml', __FILE__)))
  config.merge! config.fetch(Rails.env, {})
  config.each do |key, value|
    ENV[key] ||= value.to_s unless value.kind_of? Hash
  end
end

module ModuleUpgrade
  class Application < Rails::Application
  end
end

Need Your Help Guys! Thanks

2

There are 2 answers

7
spickermann On

I would change two things. How you load the file and how you fetch and merge the sub hash for the environment:

Bundler.require(*Rails.groups)

file = Rails.root.join('config', 'application.yml')
if File.exists?(file)
  config = YAML.load(file).fetch(Rails.env, {})
  config.each do |key, value|
    ENV[key] ||= value unless value.kind_of?(Hash)
  end
end
3
Glenn Gillen On

I don't think the path you've specified for application.yml, File.expand_path('../application.yml', __FILE__), is accurate. Try this:

app_config = File.join(Rails.root, 'config', 'application.yml')
if File.exists?(app_config)
  config = YAML.load(File.read(app_config))
  config.merge! config.fetch(Rails.env, {})
  config.each do |key, value|
    ENV[key] ||= value.to_s unless value.kind_of? Hash
  end
end

Alternatively the figaro gem attempts to make this easier for you if you don't want to roll it yourself.