在 initialize 方法之后运行一个方法 [英] Running a method after the initialize method

查看:41
本文介绍了在 initialize 方法之后运行一个方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想编写一些在调用 initialize 方法后运行的 ruby​​ 代码.此代码可以在类或模块中.我该怎么写?

I would like to write some ruby code that runs after the initialize method is called. This code can be in a class or a module. How would I write this?

这是我想要的示例:

class Base
  def after_init
    puts "after init"
  end

class A < Base # Option 1, use a class
end

class B < Base
  def initialize
    puts "in init"
  end
end

module MyMod
  def after_init
    puts "after init"
  end
end

class C
  include Module
end

$> A.new
=> "after init"
$> B.new
=> "in init"
=> "after init"
$> C.new
=> "after init"

我绝对不想做的是显式调用super.有没有办法做到这一点?我不在乎它是否使用了很多 Ruby 的反射能力.谢谢!

What I definitely don't want to do is make an explicit call to super. Is there a way to do this? I don't care if it uses a lot of Ruby's reflective abilities. Thanks!

推荐答案

class Base
  def after_init
    puts "Base#after_init"
  end

  def self.inherited(klass)
    class << klass
      alias_method :__new, :new
      def new(*args)
        e = __new(*args)
        e.after_init
        e
      end
    end
  end
end

module MyMod
  def after_init
    puts "MyMod#after_init"
  end
  def self.included(klass)
    class << klass
      alias_method :__new, :new
      def new(*args)
        e = __new(*args)
        e.after_init
        e
      end
    end
  end
end

class A < Base
end

class B < Base
  def initialize
    puts "B#initialize"
  end
end

class C
  include MyMod
  def initialize
    puts "C#initialize"
  end
end

A.new
B.new
C.new

这篇关于在 initialize 方法之后运行一个方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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