[英]How to make class\object available globally in rails?
Seems like a simple enough question but I can't seem to find an answer on SO. 看起来像一个简单的问题,但我似乎无法在SO上找到答案。
I'm trying to implement Stripe into an application. 我正在尝试将Stripe实现到应用程序中。 Stripe
is a ruby class which has a api_key
method to set the key. Stripe
是一个ruby类,它有一个api_key
方法来设置密钥。
Where in my Rails 4 app do I need to define the key as Stripe.api_key = mykey
such that Stripe
can be accessed from all of the controllers and models? 在我的Rails 4应用程序中,我需要将键定义为Stripe.api_key = mykey
,以便可以从所有控制器和模型访问Stripe
?
For example, upon account creation in the DB, I want a before_create
hook to take advantage of this Stripe
class to create a corresponding payment account. 例如,在DB中创建帐户后,我想要一个before_create
挂钩来利用此Stripe
类来创建相应的支付帐户。 It doesn't seem right to have to set the API key more than once. 不止一次设置API密钥似乎是不对的。
I've tried making it a $stripe global but I was warned against using that. 我已经尝试将其设为$ stripe全球但我被警告不要使用它。
I have a folder classes under app, in which I put a separate file per class, in your case called stripe.rb 我在app下有一个文件夹类,其中我为每个类放了一个单独的文件,在你的情况下叫做stripe.rb
This way you can use the class without doing any additional requires 这样您就可以在不执行任何其他要求的情况下使用该类
I usually place such classes inside the lib folder. 我通常将这些类放在lib文件夹中。 You need to be sure your file name is the same as your class name in snakecase. 您需要确保您的文件名与snakecase中的类名相同。
First time you use Stripe constant, rails constant_missing method is executed. 第一次使用Stripe常量时,执行rails constant_missing方法。 It searches for a file called stripe.rb in one of your autoload paths. 它在您的一个自动加载路径中搜索名为stripe.rb的文件。 If the file doesn't exist constant missing exception is thrown, otherwise it returns declared in this file class (if its name matches the constant). 如果文件不存在,则抛出常量缺失异常,否则返回此文件类中声明的内容(如果其名称与常量匹配)。
If you want to execute some code against this class on server startup, you need to put it inside config/initializers folder (not the class itself, only the code which calls it). 如果你想在服务器启动时对这个类执行一些代码,你需要将它放在config / initializers文件夹中(不是类本身,只是调用它的代码)。 All the files in this folder are being executed right after the right environment has been loaded (no naming convention required here). 在加载正确的环境后立即执行此文件夹中的所有文件(此处不需要命名约定)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.