Skip to content

Instantly share code, notes, and snippets.

@therabidbanana
Forked from gmoeck/some_controller.rb
Created July 11, 2012 14:41
Show Gist options
  • Save therabidbanana/3090830 to your computer and use it in GitHub Desktop.
Save therabidbanana/3090830 to your computer and use it in GitHub Desktop.
Simplified version of the application design I'm heading toward (actually in Sinatra, but that doesn't really matter here)
class ApplicationController
# Sharing the setup of processors, since many actions will use them
# - thinking of switching this out for a facade
def trigger_processor(name, listening_controller)
processor_klass = processors[name]
processor = processor_klass.new(params)
processor.add_listener(EventNotifier.new)
processor.add_listener(listening_controller)
processor.process(current_user)
end
def processors
{ 'new_comment' => CommentProcessor }
end
def current_user
# Returns an object that responds_to?(:can?) so we can authorize
end
end
class CommentsController < ApplicationController
def create
trigger_processor('new_comment', self)
end
def new_comment_success(comment)
# redirect
end
def new_comment_error(comment)
# show error
end
end
#example class
class CommentProcessor
def initialize(params)
@announcer = Announcer.new
@params = params
end
def repo
CommentsRepo.new
end
def add_listener(listener)
@announcer.add_listener listener
end
def process(user)
if before_filters(user)
new_comment = Comment.new(@params)
# May refactor this to pass announcer on to Comments repo.
if repo.save(new_comment)
@announcer.announce('new_comment_success', new_comment)
else
@announcer.announce('new_comment_error', new_comment)
end
end
end
def before_filters(user)
if user.can?(:create_comment)
true
else
@announcer.announce('new_comment_error', new_comment)
false
end
end
end
@therabidbanana
Copy link
Author

The main difference here from the original gist is that the processor can announce both success and failures, and those can be handled separately - the notifier may notify social networks only on success.

Not sure to handle the before filter - in certain cases I want to announce authorization failures so they can be logged, so leaving that in the controller seems like it'd have to know too much about about announcing.

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