Challenge 3: Protecting a Controller — Solution # app/controllers/application_controller.rb class ApplicationController < ActionController::Base private def current_user @current_user ||= User.find_by(id: session[:user_id]) end helper_method :current_user def require_login unless current_user redirect_to new_session_path, alert: "Please log in first" end end end # app/controllers/comments_controller.rb class CommentsController < ApplicationController before_action :require_login, except: [:index, :show] # ... the seven actions from Course 1, Chapter 3 end =begin Notes: - current_user uses ||= so User.find_by only runs once per request no matter how many times current_user is called during that request -- the second and later calls just return the already-cached @current_user value. - helper_method :current_user makes the controller method available inside views too (e.g. checking <% if current_user %> in a layout to show a login/logout link) -- without it, current_user would only be callable from controller code. - before_action :require_login, except: [:index, :show] on CommentsController means anyone (logged in or not) can browse the comments list and view individual comments, but creating, editing, or deleting a comment requires require_login to pass first -- the same selective-guarding shape as express2-1's auth middleware applied to specific Express routes rather than every route uniformly. - If require_login redirects, the guarded action's own code never runs at all -- before_action can halt the request entirely by redirecting, exactly like calling return early from Express middleware without calling next(). =end