Skip to content

Instantly share code, notes, and snippets.

@lukeredpath
Created September 15, 2011 12:54
Show Gist options
  • Select an option

  • Save lukeredpath/1219164 to your computer and use it in GitHub Desktop.

Select an option

Save lukeredpath/1219164 to your computer and use it in GitHub Desktop.
A better controller?
class WidgetsController
def index
IndexedResourceCommand.new(Widget).execute(params, default_responder)
end
def create
CreateResourceCommand.new(Widget).execute(params, default_responder)
end
private
def default_responder
# could have a different responder for different content-types (e.g. respond_to)
RenderOrRedirectResponder.new(self) # needs self to get access to controller rendering behaviour
end
end
class ResourceCommand
def initialize(scope)
@scope = scope
end
end
class IndexResourceCommand
def execute(params, responder)
responder.respond_with_collection(@scope.all)
end
end
class CreateResourceCommand
def execute(params, responder)
instance = @scope.new(params)
if instance
responder.respond_with_saved_object(instance)
else
responder.respond_with_unsaved_object(instance)
end
end
end
class RenderOrRedirectResponder
def respond_with_collection(collection)
# set up assigns and render the appropriate template
end
def respond_with_saved_object(object)
@controller.redirect_to url_for(object)
end
def respond_with_unsaved_object(object)
# set up assigns and render template with errors
end
end
@gmoeck
Copy link

gmoeck commented Sep 16, 2011

So if I understand you right, your basically using the controller as a port where data comes in? If you were to cover them with integration tests, what would you assert on?

@lukeredpath
Copy link
Author

Well, I guess that would depend on the user stories.

I have no idea if this would actually be a good design having not explored it further, more than anything I feel that Rails controllers are probably the weakest part of an app from an OOP point of view and I'm interested in ways of investigating a better approach, whether or not this is it. :)

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