Executing a mixin method at the end of a class definition

吃可爱长大的小学妹 提交于 2019-12-06 15:58:13

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!