Ruby – Why put a module in a class?

微信扫一扫,分享到朋友圈

Ruby – Why put a module in a class?

In Ruby, I see that it can be useful to put classes inside modules for the sake of namespacing. I also see that it’s possible to put modules inside classes. But I don’t see why you’d do that.

Modules are generally mixed into classes, right? So what would be the purpose of defining a module inside a class?

(I also noticed that Googling “ruby ‘module inside a class'” gets 3 results, whereas “ruby ‘class inside a module'” gets more than 18,000, so maybe the answer is “nobody does this”?)

Cool, I didn’t know you could do that. We could use it when writing ape-like code like this:

class DrugDealer
  module Drug
    def happy?; true; end
  end

  def approach(victim)
    victim.extend Drug
  end
end

o = Object.new
DrugDealer.new.approach(o)
o.happy? # => true

Edit: A better example! This is actually somewhat practical — Mixins that are only applied by subclasses. It is useful when some facets of a thing apply to some subclasses and other facets apply to other subclasses, without there being enough order in the way these aspects apply to make way for a clear class hierarchy (tree). Whew.. Think multiple inheritance. A simplified example:

class Person
  def handshake
    :sloppy
  end

  def mind_contents
    :spam
  end

  module Proper
    def handshake
      :firm
    end
  end

  module Clever
    def mind_contents
      :theories
    end
  end
end

class Professor < Person
  include Proper
  include Clever

  # ...
end

And so on.. kind of nice, when used sensibly. Even super calls and constructors (i didn’t define any here though) flow through all the mixins and classes the way i want them to. Smooth!

微信扫一扫,分享到朋友圈

Ruby – Why put a module in a class&quest;

react native input 组件简单封装

上一篇

浅谈数据中心100G光模块

下一篇

你也可能喜欢

Ruby – Why put a module in a class&quest;

长按储存图像,分享给朋友