Tell me more ×
Code Review Stack Exchange is a question and answer site for peer programmer code reviews. It's 100% free, no registration required.

Is there a way to optimize the following if/else statement?

if current_user
  if current_user.id == @user.id
    render 'item'
  else
    render 'item_friend'
  end
else
  render 'item'
end
share|improve this question

3 Answers

What about:

if !current_user || current_user.id == @user.id
  render 'item'
else
  render 'item_friend'
end
share|improve this answer
nine upvotes in two days (including mine)... I wish the C#-folks were as upvote-happy as the ruby folks ;) – codesparkle Aug 15 '12 at 0:38
@codesparkle Amazing :) And I don't even know Ruby. – Sulthan Aug 15 '12 at 10:26

This is a little more dryer

render case 
       when current_user.nil?,current_user.id == @user.id; 'item'
       else 'item_friend'
       end
share|improve this answer
  1. You can move the case when user is not signed in to another place (helper, base controller or something else).

  2. You can move the logic for selecting a view template to a separate method.


before_filter :render_items_if_current_user_blank, :only => :foobar

# action
def foobar
  @user = User.find(params[:id]) # or something else
  render_user(@user)
end

private

def render_items_if_current_user_blank
  render 'item' unless current_user
end

def render_user
  if current_user.id == @user.id
    render 'item'
  else
    render 'item_friend'
  end
end
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.