Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
sketch for Matt Wynne
class Organization
def to_param
"42"
end
def saved?
rand > 0.5
end
end
class Protocol
class << self
def message(name)
@messages ||= []
@messages << name
end
attr_reader :messages
end
def initialize(callbacks)
@callbacks = callbacks
end
def method_missing(name, *args)
super unless self.class.messages.include?(name)
@callbacks[name].call(*args)
end
end
class OrganizationCreator
class Listener < Protocol
message :success
message :failure
end
def create_for(user, org_name, listener)
# real creation logic here
organization = Organization.new
if organization.saved?
listener.success(organization)
else
listener.failure(organization)
end
end
end
class OrganizationsController
def create
params = { organization: 'Hello' }
creator = OrganizationCreator.new
creator.create_for(current_user, params[:organization],
OrganizationCreator::Listener.new(
success: ->(org) { redirect_to organizations_path(org) },
failure: ->(org) { render :error }
)
)
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
@mikegehard
Copy link

mikegehard commented Jul 3, 2012

This is an interesting way to thing about this problem. I like that from that simple snippet, you can get a good idea of what the "workflow" needs as far as parameters as well as see what the valid end states are.

Thanks for sharing!

@mattwynne
Copy link
Author

mattwynne commented Jul 3, 2012

This is just an idea - please don't anybody copy it as though it were some kind of best practice!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment