Wynn Netherland changelog.com/posts

Focused Controller - Aiming for "real OOP" in Rails controllers

While Rails controllers are Ruby classes and have some OOP support as a result, the lack of true encapsulation and awkward before_filter-based sharing of code between actions leave some OOP die hards disappointed. Jon Leighton’s Focused Controller is an early stage project that takes a different approach. Controllers are Ruby modules and actions are classes classes that inherit ultimately from ApplicationController:

module PostsController
  # Action is a common superclass for all the actions
  # inside `PostsController`.
  class Action < ApplicationController
    include FocusedController::Mixin

  class Index < Action
    def run
      # Your code here.

    # No instance variables are shared with the view. Instead,
    # public methods are defined.
    def posts
      @posts ||= Post.all

    # To prevent yourself having to write `controller.posts`
    # in the view, you can declare the method as a helper
    # method which means that calling `posts` automatically
    # delegates to the controller.
    helper_method :posts

  # Actions do not need to declare a `run` method - the default
  # implementation inherited from `FocusedController::Mixin` is an
  # empty method.
  class Show < Action
    def post
      @post ||= Post.find params[:id]
    helper_method :post

Since routes need to be modified to point to this new convention of Controller::Action#run, a helper is provided for your routes file that supports the usual syntax:

focused_controller_routes do
  resources :posts

Jon is looking for feedback so check out the README for advanced usage, especially on how to test this new style of controller.


Sign in or Join to comment or subscribe

Player art
  0:00 / 0:00