ruby模块有构造函数吗?

时间:2011-11-12 17:02:55

标签: ruby constructor module mixins

扩展时调用的东西。

EG。这段代码:

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)

1 个答案:

答案 0 :(得分: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
相关问题