Reputation: 6121
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.
Upvotes: 2
Views: 1089
Reputation: 44715
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).
Upvotes: 1
Reputation: 6025
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
Upvotes: 1