2010-05-20 64 views
2

是否有将params传递给混合方法的最佳实践方法?Ruby混合和实例变量

使用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 

......还是别的什么?

+0

你能给出一个混合方法和他们需要的参数的例子吗? – mikej 2010-05-20 16:42:41

回答

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。

+0

谢谢,但我的问题的目的是为了理解插件将使用的设置实例变量与插件方法的显式传递参数之间的更好方法(如果有的话)。 – Harv 2010-05-20 20:52:24