Created
July 17, 2013 14:19
-
-
Save Papillard/6020958 to your computer and use it in GitHub Desktop.
Use presenter if the controller is full of instance variables. Memoize instance variables !
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
| # => config/application.rb | |
| config.autoload_paths = %W(#{config.route}/presenters) # loading the file defining the presenter | |
| #/app/presenters/tweets/show_presenter | |
| module Tweets | |
| class ShowPresenter | |
| extend ActiveSupport::Memoizable # Module of class instance methods : memorize instante variables | |
| def initialize(tweet) | |
| @tweet = tweet | |
| end | |
| def username | |
| @tweet.user.username | |
| end | |
| def status | |
| @tweet.status | |
| end | |
| def favorites_count | |
| @tweet.favorites.count | |
| end | |
| memoize :username, :status, :favorites_count # alternative => username ||= @tweet.user.username | |
| end | |
| end | |
| # Tweets controller | |
| class TweetsController < ApplicationController | |
| include Tweets | |
| def show | |
| @presenter = ShowPresenter.new( Tweet.find(params[:id]) ) | |
| end | |
| end | |
| #/app/views/tweets/show.html.erb | |
| # => <%= @presenter.username.body %> | |
| # => <%= @presenter.username.favorites_count %> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment