Created
January 19, 2011 19:57
-
-
Save Gregg/786741 to your computer and use it in GitHub Desktop.
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
# if you look at your logged in twitter page, there's a crapload of information. You might expect a controller like: | |
def index | |
@followers_tweets = current_user.followers_tweets.limit(20) | |
@recent_tweet = current_user.tweets.first | |
@following = current_user.following.limit(5) | |
@followers = current_user.followers.limit(5) | |
@recent_favorite = current_user.favorite_tweets.first | |
@recent_listed = current_user.recently_listed.limit(5) | |
if current_user.trend_option == "worldwide" | |
@trends = Trend.worldwide.by_promoted.limit(10) | |
else | |
@trends = Trend.filter_by(current_user.trend_option).limit(10) | |
end | |
.... | |
end | |
# Testing this could be a nightmare ... sloppy and hard to test!. Might be cleaner to create our own presenter | |
class Tweets::IndexPresenter | |
def initialize(user) | |
@user = user | |
end | |
def followers_tweets | |
@user.followers_tweets.limit(20) | |
end | |
def recent_tweet | |
@user.tweets.first | |
end | |
... | |
def trends | |
if @user.trend_option == "worldwide" | |
Trend.worldwide.by_promoted.limit(10) | |
else | |
Trend.filter_by(@r.trend_option).limit(10) | |
end | |
end | |
end | |
# You might even store this in a /app/presenters/tweets/index_presenter.rb file. If you just created that presenters directory, you'd want to open up your config/application.rb and add: | |
config.autoload_paths += %W(#{config.root}/presenters) | |
# Then in your controller all you do is: | |
def index | |
@presenter = Tweets::IndexPresenter.new(current_user) | |
end | |
# Then in your view you just access the presenter to get the data | |
# <%= @presenter.recent_tweet.body %> | |
# <%= @presenter.recent_tweet.created_at %> | |
# If you call these items multiple times like this.. you should probably be memoizing the items in your presenter | |
class Tweets::IndexPresenter | |
def initialize(user) | |
@user = user | |
end | |
def followers_tweets | |
@followers_tweets ||= @user.followers_tweets.limit(20) | |
end | |
def recent_tweet | |
@recent_tweet ||= @user.tweets.first | |
end | |
... | |
end | |
# However, there's a shortcut for memoization which does the same thing | |
class Tweets::IndexPresenter | |
extend ActiveSupport::Memoizable | |
def initialize(user) | |
@user = user | |
end | |
def followers_tweets | |
@user.followers_tweets.limit(20) | |
end | |
def recent_tweet | |
@user.tweets.first | |
end | |
... | |
memoize :followers_tweets, :recent_tweet | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment