Created
April 22, 2012 02:25
-
-
Save tatey/2441508 to your computer and use it in GitHub Desktop.
Idea for good defaults that are easy to opt-out of with John Leighton's Focus Controllers
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| class PostsController | |
| # You could believe we have a FcousedAction module that gives us | |
| # good defaults. It exposes things like +action+ for defining | |
| # normal RESTful actions. | |
| include FocusedActions | |
| # Example 1: | |
| # The default behaviour is enough. | |
| action :index | |
| action :create | |
| # Example 2: | |
| # The default behaviour is almost enough. We have our own way of finding | |
| # posts and opt-out of the default. | |
| # | |
| # Under the hood, +action+ uses this class and works out the name from | |
| # the controller. Or something like that. | |
| class Show < FocusedActions::Action::Show | |
| exposes :post, { Post.find_by_slug(params[:slug]) } | |
| end | |
| # Example 3: | |
| # We need to do something very different. Opt-out of the default | |
| # behaviour entirely. | |
| # | |
| # Under the hood, FocusedActions::Action does something like this | |
| # for us. | |
| class Destroy | |
| include FocusedController::Mixin | |
| attr_writer :post | |
| def run | |
| if post.comments.any? | |
| render :destroy, :alert => t('posts.destroy.failure') | |
| else | |
| post.destroy | |
| redirect_to :index | |
| end | |
| end | |
| def post | |
| @post ||= Post.find_by_slug(params[:slug]) | |
| end | |
| helper_method :post | |
| end | |
| end |
Author
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
The idea is that the highest level is simply the composition of smaller components which you can peel back the further you need to customise. Each action is isolated and can easily be swapped out for another one.