Skip to content

Instantly share code, notes, and snippets.

@bnadlerjr
Last active December 11, 2018 15:55
Show Gist options
  • Save bnadlerjr/568fe286f0aa06fbe83b to your computer and use it in GitHub Desktop.
Save bnadlerjr/568fe286f0aa06fbe83b to your computer and use it in GitHub Desktop.
Rails Controller Example with Command Object
class WidgetController < ApplicationController
def new
# ...
end
def create
AddWidgetToInventory.call(widget_params) do |on|
on.success do |widget|
redirect widget_path(widget), flash: "Successfully created widget"
end
on.failure do |widget|
@widget = widget
render "widgets/new"
end
end
end
end
class AddWidgetToInventory
def self.call(params, &block)
new(params, &block).call
end
def initialize(params, &block)
@params = params
@handlers = ProcHash[block]
end
def call
widget = Widget.new
# complicated business logic
# if something fails:
handlers.respond_with(:failure, widget)
# everything is ok
handlers.respond_with(:success, widget)
end
end
class ProcHash
def self.[](block)
self.new.tap { |proxy| block.call(proxy) }
end
def respond_with(callback, *args)
callbacks[callback].call(*args)
end
def method_missing(method, *args, &block)
block ? callbacks[method] = block : super
self
end
private
def callbacks
@callbacks ||= {}
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment