An Interest In:
Web News this Week
- April 1, 2024
- March 31, 2024
- March 30, 2024
- March 29, 2024
- March 28, 2024
- March 27, 2024
- March 26, 2024
March 10, 2021 01:00 pm GMT
Original Link: https://dev.to/swanson/sharing-common-code-between-rails-controllers-with-scoped-pattern-471m
Sharing common code between Rails controllers with `Scoped` pattern
If you follow a strict REST / nested resources approach to building your Rails app, you might get sick of repeating common controller actions.
Try the Scoped
concern pattern: a place to put shared code (setting variables, authorization) and slim down your controllers.
Usage
This particular pattern comes from DHH and Basecamp a codebase that prides itself of using lots of tiny concerns to share bits of behavior.
While the savings of repeating the same before_action
s to look up a Channel
would be a fine benefit on its own, the naming convention of Scoped
is such a great, sharp name. Playlists are scoped to a channel so it makes total sense that the corresponding controller would be channel scoped.
module ChannelScoped extend ActiveSupport::Concern included do before_action :set_channel, :authorize_channel end private def set_channel @channel = Channel.find(params[:channel_id]) end def authorize_channel authorize @channel # check that user has access, etc endendclass Channels::SubscriptionsController < ApplicationController include ChannelScopedendclass Channels::VideosController < ApplicationController include ChannelScopedendclass Channels::PlaylistsController < ApplicationController include ChannelScopedend
Additional Resources
DHH Gist: Models for Nested Resources
Original Link: https://dev.to/swanson/sharing-common-code-between-rails-controllers-with-scoped-pattern-471m
Share this article:
Tweet
View Full Article
Dev To
An online community for sharing and discovering great ideas, having debates, and making friendsMore About this Source Visit Dev To