【问题标题】:Ruby Mixins and Instance variablesRuby Mixins 和实例变量
【发布时间】:2011-02-21 23:37:57
【问题描述】:

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

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

...还是别的什么?

【问题讨论】:

  • 你能举个例子说明混入的方法和需要的参数吗?

标签: ruby mixins


【解决方案1】:

我认为你应该能够做到:

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。

【讨论】:

  • 谢谢,但我的问题确实旨在了解设置插件将使用的实例变量与向插件方法显式传递参数之间的更好方法(如果有的话)。
猜你喜欢
  • 2012-09-17
  • 1970-01-01
  • 2014-09-21
  • 2011-08-27
  • 2014-03-06
  • 2013-05-28
  • 1970-01-01
  • 1970-01-01
  • 2018-12-22
相关资源
最近更新 更多