gpt4 book ai didi

ruby - 是否可以混合模块方法?

转载 作者:行者123 更新时间:2023-12-04 10:44:42 26 4
gpt4 key购买 nike

假设我有一个声明模块方法的模块( 不是 一个实例方法):

module M
def self.foo
puts 'foo'
end
end

现在假设我想混入 M.foo进入另一个类(class) C这样 C.foo被定义为。

最后,我想做这个 不改变方式M.foo定义不只是在 C 中创建方法调用 M.foo . (即重写 foo 作为实例方法不算数。使用 module_function 也不算数。)

这在 Ruby 中是不可能的吗?

最佳答案

I want to do this without changing the way M.foo is defined



不幸的是,这是不可能的。 Ruby 只允许包含模块,而不是类。 foo但是在 M 上定义的单例类,这是一个类。因此,您不能 include它。同样的限制适用于 extend .尝试这样做会导致 TypeError :
module M
def self.foo
puts 'foo'
end
end

class C
extend M.singleton_class # TypeError: wrong argument type Class (expected Module)
end

但是,您可以通过定义 foo 来实现您想要的。作为单独模块中的实例方法,然后可以混合到两者中, MC通过 extend : (该模块不必嵌套在 M 下)
module M
module SingletonMethods
def foo
puts 'foo'
end
end

extend SingletonMethods # <- this makes foo available as M.foo
end

class C
extend M::SingletonMethods # <- this makes foo available as C.foo
end


或者使用 Ruby 的 included 使用一些元编程魔法打回来:
module M
module SingletonMethods
def foo
puts 'foo'
end
end

extend SingletonMethods

def self.included(mod)
mod.extend(SingletonMethods)
end
end

class C
include M
end

这是 ActiveSupport::Concern 的简化版本。在 Rails 中工作。

关于ruby - 是否可以混合模块方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59761386/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com