class PaymentService
def initialize
Stripe.api_key = Rails.application.credentials.stripe[:secret_key]
end
def create_payment_intent(amount:, currency: 'usd')
Stripe::PaymentIntent.create(
amount: amount,
currency: currency
)
end
end
# Encrypted file, edit with: rails credentials:edit --environment production
secret_key_base: [encrypted]
database:
url: postgresql://user:pass@host:5432/dbname
redis:
url: redis://redis-host:6379/0
stripe:
publishable_key: pk_live_...
secret_key: sk_live_...
webhook_secret: whsec_...
aws:
access_key_id: AKIA...
secret_access_key: [encrypted]
region: us-east-1
bucket: production-uploads
jwt_secret: [encrypted]
Storing secrets in environment variables works but gets messy at scale with dozens of keys. Rails encrypted credentials provide a structured alternative where secrets live in version-controlled credentials.yml.enc files, encrypted with a master key stored outside the repo. I can have environment-specific credentials like credentials/production.yml.enc that override shared defaults. The rails credentials:edit command decrypts, opens an editor, and re-encrypts on save. This approach keeps sensitive configuration centralized and auditable while preventing accidental commits of plaintext secrets. The master key must be injected at deploy time via RAILS_MASTER_KEY env var or config/master.key file. I organize credentials hierarchically with namespaces for each service.
Related snips
class CommentsController < ApplicationController
before_action :set_post
def create
@comment = @post.comments.build(comment_params)
System test: asserting Turbo Stream responses
class Post < ApplicationRecord
belongs_to :author, class_name: 'User'
has_many :comments, dependent: :destroy
scope :published, -> { where.not(published_at: nil).where('published_at <= ?', Time.current) }
scope :draft, -> { where(published_at: nil) }
ActiveRecord scopes for reusable query logic
payload = {
sub: user.id,
iss: 'https://auth.example.com',
aud: 'codesnips-api',
exp: 15.minutes.from_now.to_i,
iat: Time.now.to_i,
JWT issuance and verification without common footguns
module Api
module V1
class UsersController < BaseController
def show
user = User.includes(:profile).find(params[:id])
ETags for conditional requests and caching
class PostsController < ApplicationController
def index
@posts = Post.includes(:author)
.order(created_at: :desc)
.page(params[:page])
.per(10)
Turbo Frames: infinite scroll with lazy-loading frame
require "csv"
class PeopleCsvStream
include Enumerable
HEADERS = %w[id full_name email signed_up_at plan].freeze
Resilient CSV Export as a Streamed Response
Share this code
Here's the card — post it anywhere.