⏱️
Before Action & Callbacks
액션 실행 전후에 공통 로직을 끼워넣는 방법
Controller Callback(흔히 Filter라 불림)은 액션 실행 전후에 특정 메서드를 자동으로 호출하는 기능입니다.
종류:
before_action— 액션 실행 전 (가장 많이 사용)after_action— 액션 실행 후around_action— 액션 전후를 감싸기
주요 사용 패턴:
class PostsController < ApplicationController
before_action :authenticate_user! # 인증 확인
before_action :set_post, only: [:show, :edit, :update, :destroy] # 공통 데이터 로딩
before_action :authorize_post!, only: [:edit, :update, :destroy] # 권한 확인
private
def set_post
@post = Post.find(params[:id])
end
end
only: / except: 옵션으로 특정 액션에만 적용하거나 제외할 수 있습니다. skip_before_action으로 상속받은 콜백을 건너뛸 수도 있습니다.
before_action에서 redirect_to나 render를 호출하면 체인이 중단되고 액션이 실행되지 않습니다.
핵심 포인트
1
before_action :method_name으로 콜백 등록
2
only: / except: 옵션으로 적용 범위 지정
3
액션 실행 전에 등록된 before_action들이 순서대로 실행
4
before_action에서 redirect/render 시 체인 중단 → 액션 실행 안 됨
5
skip_before_action으로 상속받은 콜백 건너뛰기
6
여러 before_action은 등록 순서대로 실행
장점
- ✓ 공통 로직을 DRY하게 관리
- ✓ 선언적이라 의도가 명확
- ✓ 상속을 통한 계층적 콜백 관리
- ✓ 액션별 세밀한 제어 (only/except)
단점
- ✗ 콜백이 많아지면 실행 순서 파악 어려움
- ✗ 암묵적 동작이라 디버깅 어려울 수 있음
- ✗ skip_before_action 남발 시 코드 혼란
- ✗ 과도한 콜백은 Controller를 복잡하게 만듦
사용 사례
인증 확인 (authenticate_user!)
리소스 로딩 (set_post, set_user)
권한 확인 (authorize!)
로깅, 감사 추적 (after_action)