Search code examples
ruby-on-railsenvironment-variablesstripe-paymentsrails-engines

Congifure Stripe in a Rails Engine with .env


I'm having trouble setting up stripe in a Rails::Engine, This is kinda a two-fold question as the 2nd one pertains to loading the envs, which is acting funny but will get to that.

Goal here is to break out a subscription process from a big Rails application.

update So as I was typing this all out I actually got it to work. Posted answer below. Feel free to comment and provided a better way to do this.

1st question STRIPE CONFIG

question how to set up stripe in a rails engine. Separate from Parent Engine or Rails app. I have tried a few things.

2nd question loading envs

.envs are not being loaded when running a local server for the dummy app yet are being loaded in the specs.


Solution

  • Stripe Config

    #/:engine_name/engine.rb
    require "dotenv-rails"
    
    module :engine_name
      class Engine < ::Rails::Engine
        isolate_namespace :engine_name
    
        config.generators do |g|
          g.test_framework :rspec, fixture: false
          g.fixture_replacement :factory_girl, dir: 'spec/factories'
        end
    
        #load envs
        Dotenv::Railtie.load
    
        initializer "config.stripe" do |app|
          config.stripe = {
            :publishable_key => ENV['STRIPE_PUBLISHABLE_KEY'],
            :secret_key      => ENV['STRIPE_SECRET_KEY']
          }
    
          Stripe.api_key = ENV['STRIPE_SECRET_KEY']
        end
      end
    end
    

    Loading .env

    So above the initializer "config.stripe" the block is passed the parent Rails app. Which when running the dummy app locally or the engine in tests thats the dummy app. This leads to the Dummy app being the root location. The confusing part was for tests the .env was also loaded when in the Engine root path, but this would not load for the engine.

    So your .env must go in the dummy apps root. Though loaded by the Engine not the Rails::app. Though The Engine will acquire all Parent Apps ENV's. It's kinda confusing but makes sense in the end.