简体   繁体   中英

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.

I'm trying to implement Stripe into an application. Stripe is a ruby class which has a api_key method to set the 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?

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. It doesn't seem right to have to set the API key more than once.

I've tried making it a $stripe global but I was warned against using that.

I have a folder classes under app, in which I put a separate file per class, in your case called stripe.rb

This way you can use the class without doing any additional requires

I usually place such classes inside the lib folder. You need to be sure your file name is the same as your class name in snakecase.

First time you use Stripe constant, rails constant_missing method is executed. It searches for a file called stripe.rb in one of your autoload paths. 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). All the files in this folder are being executed right after the right environment has been loaded (no naming convention required here).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM