Last active
December 11, 2018 15:55
-
-
Save bnadlerjr/568fe286f0aa06fbe83b to your computer and use it in GitHub Desktop.
Rails Controller Example with Command Object
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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