Ruby Mixins和Instance变量

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

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

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

例如,这里是来自Rails Controller的代码,它需要“充当发布者”并且它调用混合方法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 

…或者是其他东西?

我想你应该能做到:

 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插件act_as_publisher。