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

混合模块中的ruby – self.class.name

发布时间:2020-12-17 03:30:46 所属栏目:百科 来源:网络整理
导读:我有一个模块,其中包含写入日志的方法.在每条消息中,我想要记录记录此消息的类的名称. 可以使用include或extend混合模块.我需要我的日志在每种情况下都有正确的类名. 蒸馏代码: module M def f self.class.name endendclass C extend M include Mendp C.f #
我有一个模块,其中包含写入日志的方法.在每条消息中,我想要记录记录此消息的类的名称.

可以使用include或extend混合模块.我需要我的日志在每种情况下都有正确的类名.

蒸馏代码:

module M
  def f
    self.class.name
  end
end

class C
  extend M
  include M
end

p C.f # => "Class"
p C.new.f # => "C"

如您所见,第一次调用错误地打印“Class”.我希望它也是“C”.

怎么做到这一点?

解决方法

无需求助于钩子,只需在self为类/模块时更改您的行为:

module M
  def f
    self.is_a?(Module) ? name : self.class.name
  end
end

class C
  extend M
  include M
end

C.f     #=> "C"
C.new.f #=> "C"

(编辑:李大同)

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

    推荐文章
      热点阅读