Saving posts, then tweeting them Here's a part of my controller and it's getting quite lengthy (the code works).

Would this code slow down the performance of my website? Can it be cleaned up and be written more efficiently? 

def create
  @post = current_user.posts.build(params[:post])

  if @post.save
    if @post.verify
      UserMailer.verify_email(@user).deliver
      redirect_to root_path
    else
      flash[:success] = "Posted"

      if @post.content.to_s.length &gt; 140 and @post.image.present?
        @twitter = Twitter::Client.new
        @twitter.update(@post.content.truncate(120)+"... " +@post.image.path.to_s)
        redirect_to root_path
      elsif @post.content.to_s.length &gt; 140
        @twitter = Twitter::Client.new
        @twitter.update(@post.content.truncate(140))
        redirect_to root_path
      elsif @post.content.to_s.length &lt;= 140 and @post.image.present?
        @twitter = Twitter::Client.new
        @twitter.update(@post.content.truncate(120)+""+@post.image.path.to_s)
        redirect_to root_path
      else @post.content.to_s.length &lt;= 140
        @twitter = Twitter::Client.new
        @twitter.update(@post.content)
        redirect_to root_path
      end
    end
  else
    @feed_items = []
    render 'static_pages/home'
  end
end
Roughly:

twitter = Twitter::Client.new

img, max = @post.image ? [@post.image.path.to_s, 120] : ["", 140]
twitter.update("#{@post.content.truncate(max)}#{img}")

redirect_to root_path


All the Twitter stuff shouldn't be in the controller, rather in a utility class. This makes testing easier, makes plugging in implementations easier, makes extension easier, and so on.

Also, truncate should be already adding the "..." if truncation was necessary.

Personally, I prefer Amit's answer. IMO it's easier to read and more obvious than mine.

I would probably tighten it up a bit after an initial review to something like this:

s = @post.image ? "#{@post.content.truncate(120)}... #{@post.image.path.to_s}"
                :    @post.content.truncate(140)
twitter.update(s)


It's formatted to highlight the similarities between the two, another option is to use string interpolation again, but it seems redundant in this particular case.

(Obviously the string creation would go into a method in some sort of support decorator etc.)

All the above is untested, but probably close.