2

是否有将参数传递给混合方法的最佳实践方法?

使用 mixin 的类可以设置混合方法期望的实例变量,或者它可以将所有必要的参数作为参数传递给混合方法。

这样做的背景是我们有一个 Rails 控制器来发布内容 - 但其他控制器甚至模型需要能够“充当发布者”,所以我将控制器方法分解为一个模块,我将混合为需要。

例如,这里是来自需要“充当发布者”的 Rails 控制器的代码,它调用了一个混合方法 question_xhtml()...

def preview
    @person = Person.find params[:id]
    @group = Group.find params[:parent_id]
    @div = Division.find params[:div_id]
    @format = 'xhtml'
    @current_login = current_login
    xhtml = person_xhtml() # CALL TO MIXED-IN METHOD
    render :layout => false
end

最终 question_xhtml 需要所有这些东西!这种方法是否合理,或者这样做会更好

def preview
    person = Person.find params[:id]
    group = Group.find params[:parent_id]
    div = Division.find params[:div_id]
    format = 'xhtml'
    xhtml = person_xhtml(person, group, div, format) # CALL TO MIXED-IN METHOD
    render :layout => false
end

...或者是其他东西?

4

1 回答 1

0

我认为你应该能够做到:

module ActAsPublisher
  def person_xhtml
    do_stuff_with(@person, @group, @div, @format, @current_login)
    # eg. use instance variable directly in the module
  end
end

class WhateverController < Application Controller
  act_as_publisher
  ...
end

如果您使用脚本/生成插件 act_as_publisher。

于 2010-05-20T19:54:58.570 回答