Controller filters & concerns
This course reads the controller filters and concerns of one Rails app. It starts with the two before_action calls in Admin::BaseController, then covers the order of the callback chain across parent and child classes, and how only: and except: narrow it. It looks at skip_before_action and the app's one CSRF skip, rescue_from and how Rails matches exceptions, and ActiveSupport::Concern in a module, in Rails and in the app. It ends with an unextracted duplication and a plain Ruby challenge.
What you'll learn
- ✓How before_action registers methods that run before every action of a controller and its subclasses
- ✓The order of inherited callbacks and how only: and except: limit them to specific actions
- ✓Why a redirect_to in a before_action stops the chain, through the performed? terminator
- ✓How skip_before_action removes verify_authenticity_token for one OAuth callback action
- ✓How rescue_from matches exceptions by class hierarchy, searching handlers from the last declared
- ✓How ActiveSupport::Concern works with included do and class_methods do blocks
Two before_action calls, guarding every admin page at once
This app's app/controllers/admin/base_controller.rb, in full:
Read the full lesson free →Curriculum
7 lessonsTwo before_action calls, guarding every admin page at once
Admin::BaseController's two before_action calls guard every admin controller that inherits from it.
before_action mechanics: order, and narrowing with only:/except:
Parent callbacks run before child callbacks, only: and except: narrow actions, and performed? halts the chain.
skip_before_action, and this app's one CSRF skip
verify_authenticity_token is an inherited before_action, and the app skips it only for the GitHub callback.
rescue_from: this app's one handler, and Rails' matching rule
The app's single rescue_from renders a contextual 404, and Rails matches handlers by class hierarchy.
ActiveSupport::Concern, tried on a module, then found inside Rails
ActiveSupport::Concern is tried on a disposable module, then found in Rails source and this app's concerns.
A small duplication this app hasn't extracted into a concern
A repeated Pagy limit line in two admin controllers shows when extracting a concern is worth it.
Putting it together: filters that run for you, and logic worth naming once
A recap of the callback chain and concerns, followed by a challenge that simulates the callback chain in plain Ruby.