将辅助方法提取到类中(解决方案 n°2)
可以解决这种清理助手的特定方法 1st 我挖出了这个旧的 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, :admin, @order]
= w.link_to "✉ Notify User of Approval/Price", [:email, :admin, @order]
= w.link_to "€ Create/Edit Order's Invoice", [:edit, :admin, @order, :invoice]
如您所见,这是将逻辑封装在一个类中并且在助手/视图空间中只有一个方法的好方法