English 中文(简体)
如何绕过Ruby中缺少模块继承的问题?
原标题:How can I get around the lack of module inheritance in Ruby?

我正在尝试使用observer模式在Ruby中创建一个组件系统。组件必须定义为模块,因为它们的存在只是为了混合到ComponentContainer中。但是,Components有一些方法,理想情况下我想在某种基类中定义这些方法,但我不能这样做,因为它们是模块。

以下是我想做的事情:

module Component
  def self.on(event, &block)
    #definition..
  end

  def self.fire(event)
    #pass event to subscribers
  end
end

module FooComponent < Component
  on :foo_event do |param1, param2|
    #...
  end
end

不同类型的组件使用onfire方法,但它们不能继承它们,因为模块不能有父级。我该怎么办?这不是红宝石色的吗?

我可以通过制作ComponentFooComponentclass来实现这一点,但我不能使用extendinclude将它们混合到Component Container中。

最佳回答

要做到这一点,一个干净的方法是使用Module#includedhook方法抽象掉extend的使用。此方法是在引用包含它的基的模块上调用的。此代码所做的是创建一个Component模块,该模块使用所需方法自动扩展基:

module Component
  def self.included(base)
    base.extend Methods
  end

  module Methods
    def on(event, &block)
      # ...
    end

    def fire(event)
      # ...
    end
  end
end

module FooComponent
  include Component

  on :foo_event do |param1, param2|
    # ...
  end
end
问题回答

如果您创建了一个名为BaseComponent的单独模块,该模块定义了所有组件模块应该具有的基本方法,然后在自定义组件中包括该BaseComponent,会怎么样。

然后,您应该仍然能够将这些自定义组件混合到ComponentContainer类中。

您可以将Component的方法扩展到您的“子”模块中:

module Component
  extend self # (only if you also want to allow calling via Component.on like in the original example)

  def on(event, &block)
    #definition..
  end

  def fire(event)
    #pass event to subscribers
  end
end

module FooComponent
  extend Component

  on :foo_event do |param1, param2|
    #...
  end
end




相关问题
Ruby parser in Java

The project I m doing is written in Java and parsers source code files. (Java src up to now). Now I d like to enable parsing Ruby code as well. Therefore I am looking for a parser in Java that parses ...

rails collection_select vs. select

collection_select and select Rails helpers: Which one should I use? I can t see a difference in both ways. Both helpers take a collection and generates options tags inside a select tag. Is there a ...

RubyCAS-Client question: Rails

I ve installed RubyCAS-Client version 2.1.0 as a plugin within a rails app. It s working, but I d like to remove the ?ticket= in the url. Is this possible?

Ordering a hash to xml: Rails

I m building an xml document from a hash. The xml attributes need to be in order. How can this be accomplished? hash.to_xml

multiple ruby extension modules under one directory

Can sources for discrete ruby extension modules live in the same directory, controlled by the same extconf.rb script? Background: I ve a project with two extension modules, foo.so and bar.so which ...

Text Editor for Ruby-on-Rails

guys which text editor is good for Rubyonrails? i m using Windows and i was using E-Texteditor but its not free n its expired now can anyone plese tell me any free texteditor? n which one is best an ...

热门标签