【问题标题】:Ruby class with a module mixin [closed]带有模块 mixin 的 Ruby 类 [关闭]
【发布时间】:2013-01-23 09:12:57
【问题描述】:

我正在尝试为 mixin 扩展一个类中的模块方法。

这是我的代码:

module Mod_1
    def bar
        puts "xxx"
    end
end

class Class_A
    include Mod_1
    def bar
        super
        puts "yyy"
     end
end

test = Class_A.new
test.bar

我能想到的最好的方法是:

module Mod_1
    def Mod_1.foo
        puts "aaa"
    end
end

class Class_A
    include Mod_1
    def foo
        Mod_1.foo
        puts "bbb"
     end
end

test = Class_A.new
test.foo

有没有更好的方法可以做到这一点?

【问题讨论】:

  • 你的代码有问题吗?如果是,那是什么?如果不是,那是什么问题?
  • 问题是有没有更好的方法可以做我想做的事。
  • 你到底想做什么?为什么这种方式对你来说不够好?
  • 可以扩展模块,但不能扩展模块方法。

标签: ruby oop


【解决方案1】:

见下文:

module Bar
    def foo
        puts "first"
    end
end

class Class_A
    include Bar
    alias old_foo foo
    def foo
        old_foo
        puts "second"
    end
end

Class_A.new.bar

返回:

"first"
"second"

这使用别名。我建议专门为 Ruby 查找它们,以了解您正在尝试做的事情。

阅读: http://ruby.about.com/od/rubyfeatures/a/aliasing.html

【讨论】:

  • 他的第一个 sn-p 工作方式相同(super)。在 1.9.3 上尝试过
  • 感谢代码有效。也会尝试使用“超级”。
  • 只有你需要把Class_A.new.bar改成Class_A.new.foo
  • 在可能的情况下使用super 应该是在别名/重命名方法之前强烈首选的,因为它遵循正确的继承链并且不会回避它。如果您给事物起别名,那么您将很难真正找到在出现问题时调用的方法。
  • 我明白了,以后一定会记住的
猜你喜欢
  • 1970-01-01
  • 2013-07-20
  • 1970-01-01
  • 2019-03-03
  • 1970-01-01
  • 1970-01-01
  • 2019-06-12
相关资源
最近更新 更多