ruby-on-rails – 清理胖导轨助手
今天,我试图干掉一些代码,我提取了一些重复的File.exists?几个辅助方法用于私有方法的代码
def template_exists?(* template)并且意外地修补了这个已经存在的Rails帮助方法.这是代码气味的一个非常明确的指标,我不需要任何继承的方法,但我继承它们.此外,我的重构方法在这个帮助器中完成了什么? 因此,这个助手做得太多,因此违反了SRP(单一责任原则).我觉得铁轨助手本身很难保留在SRP中.我正在看的助手是其他助手的超级助手,自己计算300行.它是使用javascript来掌握交互流的非常复杂形式的一部分.胖助手的方法简短而整洁,所以它并不那么糟糕,但毫无疑问,它需要分离关注点. 我该怎么出去? >将方法分成许多助手? 正如我所看到的那样,没有2是更安全的经常性的monkeypatching.也许是一个组合? 代码示例和强烈的意见赞赏! 解决方法
将助手方法提取到类中(解决方案n°2)
好的,以解决这个特定的方式来清理助手1我挖出这个旧的railscast: http://railscasts.com/episodes/101-refactoring-out-helper-object 当时它激发了我创建一个小标签系统(在我的一个应用程序中与状态机一起工作): module WorkflowHelper # takes the block def workflow_for(model,opts={},&block) yield Workflow.new(model,opts[:match],self) return false end class Workflow def initialize(model,current_url,view) @view = view @current_url = current_url @model = model @links = [] end def link_to(text,url,opts = {}) @links << url url = @model.new_record? ? "" : @view.url_for(url) @view.raw "<li class='#{active_class(url)}'>#{@view.link_to(text,url)}</li>" end private def active_class(url) 'active' if @current_url.gsub(/(edit|new)/,"") == url.gsub(/(edit|new)/,"") || ( @model.new_record? && @links.size == 1 ) end end #class Workflow end 我的观点是这样的: -workflow_for @order,:match => request.path do |w| = w.link_to "? Create/Edit an Order",[:edit,:admin,@order] = w.link_to "√ Decide for Approval/Price",[:approve,@order] = w.link_to "? Notify User of Approval/Price",[:email,@order] = w.link_to " |