在ruby中添加环境变量中的urls api键 [英] Adding urls api keys in environment variable in ruby

查看:124
本文介绍了在ruby中添加环境变量中的urls api键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个我在其中一个控制器中使用的网址。有没有更好的地方把这个网址?该网址使用API​​密钥,我想知道是否有更好的地方添加这个url和/或api密钥,以便它不会添加到控制器类代码中,并且更加可编辑?如果我将它作为环境变量或其他任何东西添加,我如何从我的控制器类访问它?谢谢。它的一个红宝石和铁路项目

I have a url that I am using in one of the controllers. Is there a better place to put this url? The url uses an API key and I was wondering if there is a better place to add this url and/or api key such that its not added in the controller class code and ergo more editable? If i add it as an environment variable or anything else how do i access it from my controller class? thank you. ITS A RUBY AND RAILS PROJECT

推荐答案

使用环境变量可能是一个好主意,如果你想保留API密码和密码脱离你的源代码。使用 ENV 对象完成代码中的访问:

Using environment variables might be a good idea if you want to keep things like API keys and passwords out of your source code. Accessing them from within your code is done with the ENV object:

my_api_key = ENV['MY_API_KEY']

要使用这种技术,您需要设置变量您的环境在启动您的应用程序之前,以及您如何做到这一点取决于您的本地设置,并且可能会因开发和生产而有所不同。

To use this technique, you need to set up the variables in your environment before launching your app, and how you do this depends on your local setup, and will likely also vary between development and production.

在开发过程中,您可以简单地设置环境变量在你的shell中,例如与bash:

In development, you can simply set the environment vars in your shell, e.g. with bash:

$ export MY_API_KEY=foobar123abc
$ rails s

现在rails会启动并访问这个环境变量。您还可以为一个命令设置变量:

Now rails will start and have access to this environment variable. You can also set variables for just a single command:

$ MY_API_KEY=foobar123abc rails s

根据服务/ api的不同,可以将其中的一些设置为默认开发/测试值 config / (或 test.rb ):

Depending on what the sevice/api is, you could set some of them to default development/test values in config/environments/development.rb (or test.rb):

ENV['MY_API_KEY'] = 'non_secret_api_key_that_can_be_shared_around'

设置环境变量生产将取决于你如何部署你的应用程序。 Phusion的有关使用如果你使用的是Passenger中的环境变量。还有一个有用的有关在Heroku上使用环境变量的文章,即使您'没有使用它们进行部署。

Setting up environment variables in production will depend on how you're deploying your app. Phusion have an article on using environment variables in Passenger if your using that. There's also a useful article on using environment variables with Heroku which is worth a read even if you're not using them for deployment.

这篇关于在ruby中添加环境变量中的urls api键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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