Skip to content

Instantly share code, notes, and snippets.

@Papillard
Created July 17, 2013 14:19
Show Gist options
  • Select an option

  • Save Papillard/6020958 to your computer and use it in GitHub Desktop.

Select an option

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 !
# => 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