Skip to content

Instantly share code, notes, and snippets.

@mikegehard
Forked from mattwynne/sketch.rb
Created July 5, 2012 00:02
Show Gist options
  • Save mikegehard/3050179 to your computer and use it in GitHub Desktop.
Save mikegehard/3050179 to your computer and use it in GitHub Desktop.
Responders implemented using a block instead of another class
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