Skip to content

Instantly share code, notes, and snippets.

@nistude
Created November 28, 2012 17:15
Show Gist options
  • Save nistude/4162623 to your computer and use it in GitHub Desktop.
Save nistude/4162623 to your computer and use it in GitHub Desktop.
Callback example
# uses exception-throwing !-methods in lower level code to communicate errors
class ApiController < ApplicationController
def update
publisher = PublishingService.new
publisher.update(params[:article], params[:author])
render_success
rescue => e
render_failure("Failed to publish article: #{e.message}")
end
...
end
class PublishingService
def initialize
@purger = CachePurger.new
end
def update(article, author)
@article = article
@author = author
update_author
update_article
end
private
def update_author
UpdatesAuthor.call(@author)
@purger.purge(author_path)
end
def update_article
UpdatesArticle.call(@article)
@purger.purge(article_path)
end
...
end
class UpdatesAuthor
def self.call(params)
Author.update_attributes!(params)
end
end
class UpdatesArticle
def self.call(params)
Article.update_attributes!(params)
end
end
class CachePurger
...
def purge(path)
@cache.purge!(path)
end
end
class ApiController < ApplicationController
def update
publisher = PublishingService.new(self)
publisher.update(params[:article], params[:author])
end
def update_success
render_success
end
def update_failure(message)
render_failure("Failed to publish article: #{message}")
end
...
end
class PublishingService
def initialize(listener)
@listener = listener
@purger = CachePurger.new
end
def update(article, author)
@article = article
@author = author
update_author
update_article
@listener.update_success
end
def update_author_failure(message)
@listener.update_failure(message)
end
def update_author_success
@purger.purge(author_path, self)
end
def purge_cache_failure(message)
@listener.update_failure(message)
end
def update_article_failure(message)
@listener.update_failure(message)
end
def update_article_success
@purger.purge(article_path, self)
end
private
def update_author
UpdatesAuthor.call(@author, self)
end
def update_article
UpdatesArticle.call(@article, self)
end
...
end
...
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment