1

我的控制器中有两个动作

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

我想知道什么是重构这个的好方法(记住 DRY)?我在网上读到我不应该试图滥用 before_filter。那我还能用什么?谢谢!

4

2 回答 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
于 2012-04-17T03:52:56.493 回答
1

最明显的是使用带有up_or_down参数的单一方法。

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
于 2012-04-17T02:31:10.987 回答