ruby - 从 Ruby 中该类包含的模块调用类方法

标签 ruby multiple-inheritance

在下面的代码中,我想调用包含 self.hello 内部模块的类的类方法 done

说明:

A::bonjour 将调用 Mod::helloB::ciao 也会调用 B::ciao

我希望能够检测 Mod::hello 中的“调用类”(A 或 B),以便能够调用 A::doneB::done

module Mod
 def self.hello
  puts "saying hello..."
 end
end

class A
 include Mod

 def self.bonjour
  Mod::hello 
 end

 def self.done
  puts "fini"
 end
end

class B
 include Mod

 def self.ciao
  Mod::hello
 end

 def self.done
  puts "finitto"
 end
end

最佳答案

虽然(也许)不像 Niklas 的答案那么干净,但它仍然很容易实现,并且 IMO 比 OP 中显示的使用模式更干净,OP 依赖于知道混合了哪个模块。

(当存在其他方法时,我不想像这样向 mixin 方法传递参数。)

输出:

pry(main)> A::bonjour
saying hello...
fini
pry(main)> B::ciao
saying hello...
finitto

胆量:

module Mod
  module ClassMethods
    def hello
      puts "saying hello..."
      done
    end
  end

  def self.included(clazz)
    clazz.extend ClassMethods
  end
end

修改后的类声明,删除显式模块引用:

class A
  include Mod

  def self.bonjour
    hello
  end

  def self.done
    puts "fini"
  end
end

class B
  include Mod

  def self.ciao
    hello
  end

  def self.done
    puts "finitto"
  end
end

您还可以提供 done 的默认实现:

module Mod
  module ModMethods
    def hello
      puts "saying hello..."
      done
    end

    def done
      throw "Missing implementation of 'done'"
    end
  end

  def self.included(clazz)
    clazz.extend ModMethods
  end
end

正如本文的评论所指出的,如果OP中的代码片段忠实地代表了实际用例,您不妨使用extend(而不是include) >),让一切变得干净:

module Mod
  def hello
    puts "saying hello..."
    done
  end

  def done
    raise NotImplementError("Missing implementation of 'done'")
  end
end

以及使用extend的类:

class A
  extend Mod

  def self.bonjour
    hello
  end

  def self.done
    puts "fini"
  end
end

关于ruby - 从 Ruby 中该类包含的模块调用类方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8761145/

相关文章:

javascript - 如何使 Javascript 生成的复选框持久化?

C++ 从接口(interface)和转换的多重继承

ruby - 为什么在 Ruby 中将 7 位 ASCII 字符串文字编码为 UTF-8

ruby-on-rails - Heroku:使用回形针运行 imagemagick

Ruby - DOS (Win32) 路径名到 NT( native )路径名

javascript - ExecJS::ProgramError: SyntaxError: 意外的标记:名称 <ClassName>

Java:你怎么称呼这种多重继承歧义?

C++:同一对象的基类与派生类的指针比较

java - 如何在 Java 中强制执行构造函数

c++ - 是否可以为复制基的虚函数提供不同的定义?