module Snips
class Create
def initialize(author:, params:)
@author = author
@params = params
end
def call
Snip.create!(@params.merge(author: @author, active_at: Time.current))
end
end
end
class SnipsController < ApplicationController
def create
snip = Snips::Create.new(author: current_member, params: snip_params).call
redirect_to snip
end
private
def snip_params
params.require(:snip).permit(:title, :content)
end
end
Command objects (a.k.a. “actions”) make controllers boring. They’re easy to test, easy to instrument, and they produce a stable API for the rest of your app. This is the kind of structure that makes large Rails apps maintainable.