1

i have two actions in my controller

def up_vote
    lesson = Lesson.find(params[:id])
    current_user.up_vote!(lesson)
    flash[:message] = 'Thanks for voting!'
    redirect_to lesson_path(lesson)
end

def down_vote
    lesson = Lesson.find(params[:id])
    current_user.down_vote!(lesson)
    flash[:message] = 'Thanks for voting!'
    redirect_to lesson_path(lesson)
end

i was wondering what would be a good way to refactor this (keeping DRY in mind)? i read online that i shouldn't be trying to abuse the before_filter. what else could i use then? thanks!

1
  • 1
    when considering code re factoring, this is a good resource - refactormycode.com Commented Apr 17, 2012 at 6:54

2 Answers 2

6
def vote_up
  vote(:up)
end

def vote_down
  vote(:down)
end

protected

def vote(direction)
  lesson = Lesson.find(params[:id])
  current_user.send :"#{direction}_vote!",lesson
  flash[:message] = 'Thanks for voting!'
  redirect_to lesson_path(lesson)
end
Sign up to request clarification or add additional context in comments.

1 Comment

thank you for your help! i will keep that idea in mind. ive never seen the .send before
1

Well most obviously would be to use a single method which takes an up_or_down parameter.

def vote(up_or_down)
    lesson = Lesson.find(params[:id])
    if up_or_down.eql? "up"
      current_user.up_vote!(lesson)
    elsif up_or_down.eql? "down"
      current_user.down_vote!(lesson)
    else
      # send an error message or just return
    end
    flash[:message] = 'Thanks for voting!'
    redirect_to lesson_path(lesson)
end

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.