是否可以在我的代码中为 rails 开发环境设置 ENV 变量? [英] Is it possible to set ENV variables for rails development environment in my code?

查看:17
本文介绍了是否可以在我的代码中为 rails 开发环境设置 ENV 变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道我可以通过 bash 设置我的 ENV 变量

I know that I can set my ENV variables in bash via

export admin_password = "secret"

但是有没有办法在我的 rails 源代码中的某个地方做到这一点?我的第一次尝试在 environment/development.rb

But is there a way to do it in my rails source code somewhere? My first attempt was something like this in environment/development.rb

ENV['admin_password'] = "secret"

但是没有用.有没有办法做到这一点?

But it didn't work. Is there a way to do this?

推荐答案

[更新]

虽然旧答案"下的解决方案适用于一般问题,但本部分将在您的评论澄清后回答您的具体问题.

While the solution under "old answer" will work for general problems, this section is to answer your specific question after clarification from your comment.

您应该能够完全按照您在问题中指定的方式设置环境变量.例如,我有一个使用 HTTP 基本身份验证的 Heroku 应用.

You should be able to set environment variables exactly like you specify in your question. As an example, I have a Heroku app that uses HTTP basic authentication.

# app/controllers/application_controller.rb
class ApplicationController < ActionController::Base
  protect_from_forgery
  before_filter :authenticate

  def authenticate
    authenticate_or_request_with_http_basic do |username, password|
      username == ENV['HTTP_USER'] && password == ENV['HTTP_PASS']
    end
  end
end

# config/initializers/dev_environment.rb
unless Rails.env.production?
  ENV['HTTP_USER'] = 'testuser'
  ENV['HTTP_PASS'] = 'testpass'
end

所以在你的情况下你会使用

So in your case you would use

unless Rails.env.production?
  ENV['admin_password'] = "secret"
end

不要忘记重启服务器以便重新加载配置!

Don't forget to restart the server so the configuration is reloaded!

[旧答案]

对于应用范围的配置,您可以考虑如下解决方案:

For app-wide configuration, you might consider a solution like the following:

创建一个文件 config/application.yml,其中包含您希望能够访问的选项的散列:

Create a file config/application.yml with a hash of options you want to be able to access:

admin_password: something_secret
allow_registration: true
facebook:
  app_id: application_id_here
  app_secret: application_secret_here
  api_key: api_key_here

现在,创建文件 config/initializers/app_config.rb 并包含以下内容:

Now, create the file config/initializers/app_config.rb and include the following:

require 'yaml'

yaml_data = YAML::load(ERB.new(IO.read(File.join(Rails.root, 'config', 'application.yml'))).result)
APP_CONFIG = HashWithIndifferentAccess.new(yaml_data)

现在,您可以在应用程序的任何位置访问 APP_CONFIG[:admin_password] 以及所有其他数据.(请注意,由于初始化程序包含 ERB.new,您的 YAML 文件可以包含 ERB 标记.)

Now, anywhere in your application, you can access APP_CONFIG[:admin_password], along with all your other data. (Note that since the initializer includes ERB.new, your YAML file can contain ERB markup.)

这篇关于是否可以在我的代码中为 rails 开发环境设置 ENV 变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆