在rails控制器中重构代码

时间:2012-04-17 02:28:18

标签: ruby-on-rails controller refactoring

我的控制器中有两个动作

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。我还能用什么呢?谢谢!

2 个答案:

答案 0 :(得分: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

答案 1 :(得分: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