ruby - 我可以扩展 Ruby 类以动态地表现得像 OpenStruct 吗?

标签 ruby module metaprogramming mixins openstruct

我有一个包含模块的 Ruby 类。我希望包含的类表现得像 OpenStruct。我如何在不显式继承 OpenStruct 的情况下实现这一目标?

class Book
  include MyModule
end

module MyModule
  def self.included(klass)
    # Make including class behave like OpenStruct
  end
end

代替

class Book < OpenStruct
  include MyModule
end

最佳答案

您可以将您的类不处理的所有方法委托(delegate)给 OpenStruct:

require 'ostruct'

class Test_OS

  def initialize
    @source = OpenStruct.new
  end

  def method_missing(method, *args, &block)
    @source.send(method, *args, &block)
  end

  def own_method
    puts "Hi."
  end

end

t = Test_OS.new
t.foo = 1
p t.foo #=> 1
t.own_method #=> Hi.

关于ruby - 我可以扩展 Ruby 类以动态地表现得像 OpenStruct 吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10760284/

相关文章:

ruby-on-rails - 如何在每个对象类型级别创建接口(interface)?

c++ - 错误 : expected primary-expression before 'template' - what am I doing wrong?

scala - 将函数实现以编程方式将特定类型返回到另一个函数中

ruby-on-rails - 无法激活 bcrypt-ruby (~> 3.0.0),已经激活 bcrypt-ruby-3.1.2

ruby-on-rails - Ruby 模块中常量的作用域

typescript - 如果我的所有导入都来 self 自己的文件,我是否需要使用 TypeScript 3.8 的 "import type"功能?

java - 具有子模块时未部署主 pom.xml

ruby-on-rails - Ruby url 到 html 链接转换

ruby - 如何按多个键排序,其中一些键按降序排列

unix - 错误: Unbound module Unix in Ocaml