ruby 31 lines · 6 steps

Wrapping Rails credentials in a gateway

A small class that reads Stripe secrets from Rails credentials and fails loudly when they're missing.

Explained by highlit
1class PaymentGateway
2 class MissingCredentialError < StandardError; end
3 
4 def initialize(env: Rails.env)
5 @env = env.to_sym
6 end
7 
8 def api_key
9 fetch(:stripe, :api_key)
10 end
11 
12 def webhook_secret
13 fetch(:stripe, :webhook_secret)
14 end
15 
16 def publishable_key
17 fetch(:stripe, :publishable_key)
18 end
19 
20 private
21 
22 def fetch(*path)
23 value = credentials.dig(*path)
24 value || raise(MissingCredentialError, "Missing credential #{path.join('.')} for #{@env}")
25 end
26 
27 def credentials
28 Rails.application.credentials.dig(@env) ||
29 raise(MissingCredentialError, "No credentials configured for #{@env}")
30 end
31end
01 / 01
STEP 01

Walkthrough

Space play step click any line
Three takeaways
  1. 1Wrapping raw credential access in named methods gives you clear call sites and a single place to change lookup logic.
  2. 2Raising a custom error at the point of a missing value surfaces misconfiguration immediately instead of as a confusing nil downstream.
  3. 3Passing the environment into the constructor keeps the class testable rather than hardwiring it to global state.

Related explainers

Share this explainer

Here's the card — post it anywhere.

Wrapping Rails credentials in a gateway — share card
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code