加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

ruby – 在initialize方法之后运行方法

发布时间:2020-12-17 01:33:04 所属栏目:百科 来源:网络整理
导读:我想编写一些在调用initialize方法后运行的 ruby代码.此代码可以在类或模块中.我怎么写这个? 这是我想要的一个例子: class Base def after_init puts "after init" endclass A Base # Option 1,use a classendclass B Base def initialize puts "in init"
我想编写一些在调用initialize方法后运行的 ruby代码.此代码可以在类或模块中.我怎么写这个?

这是我想要的一个例子:

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的反射能力.谢谢!

解决方法

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读