wangchuande

ruby module extend self vs module_funciton

最近学习ruby过程中,extend self 跟 module_function 傻傻分不清楚,查资料后明白之间的差别,虽记录之,原文地址 github

module A
  extend self

  def a
    puts 'In a'
  end

  private
  def b
    puts 'In b'
  end
end


module B
  def c
    puts 'In c'
  end
  private
  def d
    puts 'In d'
  end
  module_function :c, :d
end

A.a => In a
A.b => NoMethodError: private method b called for A:Module
B.c => In c
B.d => In d


class O
  include A
  include B
end
o = O.new => #<O:0x007f90ed2cdb18>
o.a => In a
o.b => NoMethodError: private method b called for #<O:0x007f90ed2cdb18>
o.c => NoMethodError: private method c called for #<O:0x007f90ed2cdb18>
o.d => NoMethodError: private method d called for #<O:0x007f90ed2cdb18>


总结:module_function 会将module自身的方法变为public(即使方法本身声明为private), mixin之后所有的方法都变为实例的私有方法.

posted on 2017-04-08 13:10  wangchuande  阅读(225)  评论(0编辑  收藏  举报

导航