Ruby mixin和实例变量

Ruby mixin和实例变量,ruby,mixins,Ruby,Mixins,是否有最佳实践方法将参数传递给混合方法 使用mixin的类可以设置mixed-in方法所期望的实例变量,也可以将所有必需的参数作为参数传递给mixed-in方法 这方面的背景是我们有一个Rails控制器来发布内容,但是其他控制器甚至模型都需要能够充当发布者,所以我将控制器方法分解成一个模块,我将根据需要进行混合 例如,这里是来自Rails控制器的代码,它需要充当发布者,并且它调用了一个混合方法question_xhtml def preview @person = Person.find

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

使用mixin的类可以设置mixed-in方法所期望的实例变量,也可以将所有必需的参数作为参数传递给mixed-in方法

这方面的背景是我们有一个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
最终,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

…还是别的什么?

我认为你应该能够做到:

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

如果您使用脚本/生成插件作为发布者。

我认为您应该能够做到:

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

如果您使用script/generate plugin act_as_publisher.

您能给出一个混合方法及其所需参数的示例吗?您能给出一个混合方法及其所需参数的示例吗?谢谢,但我的问题实际上是为了理解插件将使用的设置实例变量与向插件方法显式传递参数之间是否存在一种更好的方法。谢谢,但我的问题实际上是为了理解插件将使用的设置实例变量之间是否存在一种更好的方法,vs.将参数显式传递给插件方法。