-
-
Save rinaldifonseca/3074163 to your computer and use it in GitHub Desktop.
Responders implemented using a block instead of another class
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
class Organization | |
def to_param | |
"42" | |
end | |
def saved? | |
rand > 0.5 | |
end | |
end | |
class ResponseHandler | |
def handlers | |
@handlers ||= {} | |
end | |
def method_missing(name, *args, &block) | |
handler_name_to_call = handler_name(name.to_s) | |
if handler_name_to_call.nil? | |
set_handler(name,block) | |
else | |
handler = get_handler(handler_name_to_call) | |
if handler.nil? | |
super | |
else | |
handler | |
end | |
end | |
end | |
private | |
def set_handler(name, handler) | |
handlers[name] = handler | |
end | |
def get_handler(name) | |
handlers[name.to_sym] | |
end | |
def handler_name(method_name) | |
captures = method_name.scan(/\Aon_(.*)\z/).flatten | |
if captures.empty? | |
nil | |
else | |
captures.first | |
end | |
end | |
end | |
class OrganizationCreator | |
def create_for(user, org_name, &response_configuration) | |
# real creation logic here | |
organization = Organization.new | |
response_handler = ResponseHandler.new | |
response_configuration.call(response_handler) | |
if organization.saved? | |
response_handler.on_success.call(organization) | |
else | |
response_handler.on_failure.call(organization) | |
end | |
end | |
end | |
class OrganizationsController | |
def create | |
params = { organization: 'Hello' } | |
creator = OrganizationCreator.new | |
creator.create_for(current_user, params[:organization]) do |response| | |
response.success { |org| redirect_to organizations_path(org) } | |
response.failure { render :error } | |
end | |
end | |
private | |
def redirect_to(path) | |
puts "redirecting_to #{path}" | |
end | |
def render(renderable) | |
puts "rendering #{renderable}" | |
end | |
def current_user | |
Object.new | |
end | |
def organizations_path(org) | |
"/organizations/#{org.to_param}" | |
end | |
end | |
controller = OrganizationsController.new | |
controller.create |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment