refactoring code in rails controller

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!

Answers


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

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

Need Your Help

Is Erlang Object-Oriented?

erlang oop

Message-passing is a fundamental part of Erlang. Alan Kay has argued that message-passing is a concept more important than objects in his view of object-oriented programming (and he "invented" the ...

Read/Extract .ppt Document all text using c#

c# shared-libraries powerpoint

I want to extract all the text from the document .ppt file.