Created
July 1, 2015 06:13
-
-
Save dugancathal/a1a50cb924c1f49c9d9f to your computer and use it in GitHub Desktop.
Success/failure callbacks in Ruby
This file contains 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
require 'json' | |
class PostsController | |
def create | |
CreatePost.new(params) | |
.on_success(&-> { | |
render json: {}, status: 200 | |
}) | |
.on_failure(&-> { | |
render json: {errors: {name: ["can't be blank"]}}, status: 422 | |
}) | |
.on_explosion(&-> { | |
render json: {booms: "happen"}, status: 500 | |
}) | |
.execute | |
end | |
private | |
def render(options={}) | |
<<-HTTP.gsub(/^\s+/, '') | |
HTTP/1.1 #{options[:status]} | |
Content-Type: application/json | |
#{options[:json].to_json} | |
HTTP | |
end | |
def params | |
{author_id: 1, content: 'My first blog post!'} | |
end | |
end | |
class BaseExecutor | |
def initialize | |
@callbacks = {} | |
end | |
def execute | |
raise NotImplementedError | |
end | |
def method_missing(name, *args, &block) | |
method_name = name.to_s | |
if method_name.start_with?('on_') && block_given? | |
@callbacks[method_name.sub(/on_/, '')] = block | |
self | |
else | |
super | |
end | |
end | |
end | |
class CreatePost < BaseExecutor | |
def initialize(params) | |
super() | |
@params = params | |
end | |
def execute | |
@callbacks.values.sample.call | |
end | |
end | |
puts PostsController.new.create |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment