了解类方法的 method_added

发布于 2024-10-14 10:26:23 字数 484 浏览 2 评论 0原文

我想在实例和类方法添加到某个类中时做一些魔法。因此我尝试了以下方法:

module Magic
  def self.included(base)
    base.extend ClassMethods
  end  
  module ClassMethods
    def method_added(name)
      puts "class method '#{name}' added"
    end  
    def some_class_method
      puts "some class method"
    end  
  end  
end

class Foo
  include Magic
  def self.method_added(name)
    puts "instance method #{name} added"
  end  
end

这种方法对于实例方法效果很好,对于类方法则失败。我该如何解决这个问题?有什么建议吗?

I would like to do some magic in the moment instance and class methods are added to some class. Therefore I tried the following:

module Magic
  def self.included(base)
    base.extend ClassMethods
  end  
  module ClassMethods
    def method_added(name)
      puts "class method '#{name}' added"
    end  
    def some_class_method
      puts "some class method"
    end  
  end  
end

class Foo
  include Magic
  def self.method_added(name)
    puts "instance method #{name} added"
  end  
end

This approach works well for instance methods, fails for class methods. How can I solve that? Any suggestions?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

计㈡愣 2024-10-21 10:26:23

您正在寻找 singleton_method_added:

module Magic
  def self.included(base)
    base.extend ClassMethods
  end  
  module ClassMethods
    def method_added(name)
      puts "instance method '#{name}' added"
    end  

    def singleton_method_added(name)
      puts "class method '#{name}' added"
    end
  end  
end

class Foo
  include Magic

  def bla  
  end

  def blubb
  end

  def self.foobar
  end
end

输出:

instance method 'bla' added
instance method 'blubb' added
class method 'foobar' added

享受吧!

you are looking for singleton_method_added:

module Magic
  def self.included(base)
    base.extend ClassMethods
  end  
  module ClassMethods
    def method_added(name)
      puts "instance method '#{name}' added"
    end  

    def singleton_method_added(name)
      puts "class method '#{name}' added"
    end
  end  
end

class Foo
  include Magic

  def bla  
  end

  def blubb
  end

  def self.foobar
  end
end

Output:

instance method 'bla' added
instance method 'blubb' added
class method 'foobar' added

Enjoy!

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文