Skip to content

Instantly share code, notes, and snippets.

@Gregg
Created January 14, 2011 20:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save Gregg/780206 to your computer and use it in GitHub Desktop.
Save Gregg/780206 to your computer and use it in GitHub Desktop.
Fat Model / Skinny Controller
# 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