在类定义的末尾执行mixin方法 [英] Executing a mixin method at the end of a class definition

查看:74
本文介绍了在类定义的末尾执行mixin方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个混合器,可以反映接收器类以生成一些代码.这意味着我需要在类定义的末尾执行类方法,如下面这个简单的示例所示:

I have a Mix-in that reflects on the receiver class to generate some code. This means that I need to execute the class method at the end of the class definition, like in this trivially dumbed down example:

module PrintMethods
  module ClassMethods
    def print_methods
      puts instance_methods
    end
  end

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

class Tester
  include PrintMethods

  def method_that_needs_to_print
  end

  print_methods
end

我想让mixin为我自动执行此操作,但我想不出办法.我的第一个念头是在mixin中将receiver.print_methods添加到self.included,但是那行不通,因为尚未声明我希望其反映的方法.我可以在课程结束时打电话给include PrintMethods,但这感觉像是不好的形式.

I'd like to have the mixin do this for me automatically, but I can't come up with a way. My first thought was to add receiver.print_methods to self.included in the mixin, but that won't work because the method that I want it to reflect on has not been declared yet. I could call include PrintMethods at the end of the class, but that feels like bad form.

是否有任何技巧可以做到这一点,所以我不需要在类定义的末尾调用print_methods?

Are there any tricks to make this happen so I don't need to call print_methods at the end of the class definition?

推荐答案

首先,类定义没有尽头.请记住,在Ruby中,您可以在初始化"它后重新打开Tester类方法,因此解释器无法知道该类的结束"位置.

First of all, there's no end of class definition. Remember that in Ruby you can reopen the Tester class method after you have 'initialized' it, so the interpreter can't know where the class 'ends'.

我能想到的解决方案是通过一些辅助方法来制作类,例如

The solution I can come up with is to make the class via some helper method, like

module PrintMethods
  module ClassMethods
    def print_methods
      puts instance_methods
    end
  end

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

class Object
  def create_class_and_print(&block)
    klass = Class.new(&block)
    klass.send :include, PrintMethods
    klass.print_methods
    klass
  end
end

Tester = create_class_and_print do
  def method_that_needs_to_print
  end
end

但是当然必须以这种方式定义类会让我的眼睛受伤.

But certainly having to define classes this way makes my eyes hurt.

这篇关于在类定义的末尾执行mixin方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆