Created
January 14, 2011 20:48
-
-
Save Gregg/780206 to your computer and use it in GitHub Desktop.
Fat Model / Skinny Controller
This file contains 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
# A user has many tweets.. and sometimes we want to retweet. | |
class TweetsController < ApplicationController | |
def retweet | |
tweet = Tweet.find(params[:id]) | |
if tweet.user == current_user | |
flash[:notice] = "Sorry, you can't retweet your own tweets" | |
elsif tweet.retweets.where(:user_id => current_user.id).present? | |
flash[:notice] = "You already retweeted!" | |
else | |
t = Tweet.new | |
t.status = "RT #{tweet.user.name}: #{tweet.status}" | |
t.original_tweet = tweet | |
t.user = current_user | |
t.save | |
flash[:notice] = "Succesfully retweeted" | |
end | |
redirect_to tweet | |
end | |
end | |
# This is a good example where the logic belongs in a Model. So our controller turns into | |
class TweetsController < ApplicationController | |
def retweet | |
tweet = Tweet.find(params[:id]) | |
flash[:notice] = tweet.retweet_by(current_user) | |
redirect_to tweet | |
end | |
end | |
# And the logic moves to the Model. | |
class Tweet < ActiveRecord::Base | |
def retweet_by(current_user) | |
if self.user == current_user | |
"Sorry, you can't retweet your own tweets" | |
elsif self.retweets.where(:user_id => current_user.id).present? | |
"You already retweeted!" | |
else | |
t = Tweet.new | |
t.status = "RT #{self.user.name}: #{self.status}" | |
t.original_tweet = self | |
t.user = current_user | |
t.save | |
"Succesfully retweeted" | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment