before_action & Thin Controllers

Repeating yourself across show/update/destroy

show, update, and destroy all start the same way: look a walker up by params[:id]. Writing walker = Walker.find(params[:id]) three separate times isn't wrong, but it's the kind of duplication Ruby always has a DRYer answer for. A before_action runs a method before the listed actions, every time:

class Api::BookingsController < ApplicationController
  before_action :set_booking, only: %i[show destroy]

  def show
    render json: { booking: booking_payload(@booking) }
  end

  def destroy
    @booking.destroy!
    head :no_content
  end

  private

  def set_booking
    @booking = Booking.find(params[:id])
  end
end

only: %i[show destroy] scopes it β€” index and create don't have an :id to look up yet, so they'd crash if set_booking ran for them too. The lookup happens once, in one place, and every listed action can just assume @booking is already there.