Sasha
Sasha

Reputation: 3281

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!

Upvotes: 1

Views: 238

Answers (2)

ffoeg
ffoeg

Reputation: 2336

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

Upvotes: 6

Michael Berkowski
Michael Berkowski

Reputation: 270609

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

Upvotes: 1

Related Questions