【问题标题】:Do ruby modules have constructors?ruby 模块有构造函数吗?
【发布时间】:2011-11-12 17:02:55
【问题描述】:

扩展时调用的东西。

例如。这段代码:

module M
  def init(x)
    @x = 5
    self
  end
  def foo
    super
    puts @x
  end
end
class D
  def foo
    puts 1
  end
end

D.new.extend(M).init(5).foo

有效并返回 1 5。但我想将最后一行更改为阅读

D.new.extend(M.init(5)).foo

或者更好

D.new.extend(M(5)).foo

防止错误没有设置@x。

在类似的情况下,我可以说类似

class X
  include Debug(5)

【问题讨论】:

    标签: ruby constructor module mixins


    【解决方案1】:

    您可以通过使用返回模块的方法来做到这一点。

    def M(par)
      m = Module.new
      m.module_eval %Q{
        def foo
          super
          puts #{par}
        end
      }
      m
    end
    
    D.new.extend(M(5)).foo # => 5
    
    class X
      include M(4)
    end
    
    X.new.foo # => 4
    

    【讨论】:

    • 这会让编辑模块变得很痛苦。有没有办法在模块本身内部做到这一点?例如。模块 M; def self.init(x);新模式 = M; #在这里对new_mod做点什么;新模式;结尾;结束;
    • 好吧,您可以采用上述方法并将其仅用于创建需要这种处理的方法。因此,您可以在之前编写的一些现有模块上调用module_eval,而不是Module.new。但是直接回答你的问题:不,模块没有构造函数。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-07-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-19
    相关资源
    最近更新 更多