简体   繁体   English

Rails控制器中的重构代码

[英]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)? 我想知道什么是重构此方法的好方法(牢记DRY)? i read online that i shouldn't be trying to abuse the before_filter. 我在网上阅读了我不应该尝试滥用before_filter的信息。 what else could i use then? 那我还能用什么呢? thanks! 谢谢!

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. 好吧,最明显的是使用带有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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM