Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save caike/780418 to your computer and use it in GitHub Desktop.
Save caike/780418 to your computer and use it in GitHub Desktop.
# 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
render :show
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])
result_message = @tweet.retweet_by(current_user)
redirect_to(@tweet, :notice => result_message)
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