Baike.dev
All toolsOnline toolsAI codingTrendingOpen sourceNewsSubmit
Log in
< Back to tools
C

coach

> 编程语言
Open source

Alternative controllers with middleware

167 stars0 likes1 views
WebsiteGitHub

About

Alternative controllers with middleware

Coach

Coach improves your controller code by encouraging:

  • Modularity - No more tangled before_filter's and interdependent concerns. Build Middleware that does a single job, and does it well.
  • Guarantees - Work with a simple provide/require interface to guarantee that your middlewares load data in the right order when you first boot your app.
  • Testability - Test each middleware in isolation, with effortless mocking of test data and natural RSpec matchers.

For our policy on compatibility with Ruby and Rails versions, see COMPATIBILITY.md.

Installation

To get started, just add Coach to your Gemfile, and then run bundle:

ruby
gem 'coach'

Coach works with Ruby versions 3.1 and onwards.

Coach by example

The best way to see the benefits of Coach is with a demonstration.

Mounting an endpoint

…

Routing

For routes that represent resource actions, Coach provides some syntactic sugar to allow concise mapping of endpoint to handler in Rails apps.

ruby
# config/routes.rb
Example::Application.routes.draw do
  router = Coach::Router.new(self)
  router.draw(Routes::Users,
              base: "/users",
              actions: [
                :index,
                :show,
                :create,
                :update,
                disable: { method: :post, url: "/:id/actions/disable" }
              ])
end

Default actions that conform to standard REST principles can be easily loaded, with the users resource being mapped to:

Method URL Description
GET /users Index all users
GET /users/:id Get user by ID
POST /users Create new user
PUT /users/:id Update user details
POST /users/:id/actions/disable Custom action routed to the given path suffix

If you're using Zeitwerk, you can pass the name of the module to #draw, instead of the module itself.

ruby
# config/routes.rb
Example::Application.routes.draw do
  router = Coach::Router.new(self)
  router.draw("Routes::Users",
              base: "/users",
              actions: [
                :index,
                :show,
                :create,
                :update,
                disable: { method: :post, url: "/:id/actions/disable" }
              ])
end

Rendering

By now you'll probably agree that the rack response format isn't the nicest way to render responses. Coach comes sans renderer, and for a good reason.

We initially built a Coach::Renderer module, but soon realised that doing so would prevent us from open sourcing. Our Renderer was 90% logic specific to the way our APIs function, including handling/formatting of validation errors, logging of unusual events etc.

What worked well for us is a standalone Renderer class that we could require in all our middleware that needed to format responses. This pattern also led to clearer code - consistent with our preference for explicit code, stating Renderer.new_resource(...) is instantly more debuggable than an inherited method on all middlewares.

Instrumentation

Coach uses ActiveSupport::Notifications to issue events that can be used to profile middleware.

Information for how to use ActiveSupports notifications can be found here.

Event Arguments
start_handler.coach event(:middleware, :request)
start_middleware.coach event(:middleware, :request)
finish_middleware.coach start, finish, id, event(:middleware, :request)
finish_handler.coach start, finish, id, event(:middleware, :request)
request.coach event containing request data and benchmarking

Of special interest is request.coach, which publishes statistics on an entire middleware chain and request. This data is particularly useful for logging, and is our solution to Rails process_action.action_controller event emitted on controller requests.

The benchmarking data includes information on how long each middleware took to process, along with the total duration of the chain.

For coach to emit request.coach events, it first needs to be subscribed to handler/middleware events:

ruby
Coach::Notifications.subscribe!

# Now you can subscribe to and use request.coach events, e.g.
ActiveSupport::Notifications.subscribe("request.coach") do |_, event|
  Rails.logger.info(event)
end

You can add additional metadata to the notifications published by Coach by calling the log_metadata method from inside your Coach middlewares.

ruby
class Tracking  UserDecorator -> Authentication

If there are multiple paths to a middleware that provides that value, all of them will be listed. Similarly, if multiple middlewares provide the same value, all of them will be listed.

Spring integration

Given that the Coach CLI is mostly aimed at large Rails apps using Coach, it would be an oversight for us not to integrate it with Spring.

To enable the use of Spring with the Coach CLI, add the following to config/spring.rb or an equivalent Rails config file.

ruby
require "spring/commands/coach"

On GoCardless' main Rails app, using Spring reduces the time to run coach commands from around 15s to 1s.

Future work

While we think the commands we've already built are useful, we do have some ideas to go further, including:

  • Better formatting of provider chains
  • Outputting DOT format files to visualise with Graphviz
  • Editor integrations (e.g. showing the provider chains when hovering a requires statement)

License & Contributing

  • Coach is available as open source under the terms of the MIT License.
  • Bug reports and pull requests are welcome on GitHub at https://github.com/gocardless/coach.

GoCardless ♥ open source. If you do too, come join us.

Issues· 6 open

View all issuesOpen on GitHub

No open issues yet, or sync has not completed.

> Tags

Ruby

No comments yet. Be the first to share.

> Details

PublishedAug 1, 2026
UpdatedSep 18, 2026
Category编程语言
PricingOpen source

> Related tools

T
TypeScript
JavaScript 的超集,为前端与全栈提供静态类型
P
Python
通用编程语言,广泛用于 Web、数据与 AI
G
Go
Google 推出的简洁高效系统语言