Tbpgr Blog

Employee Experience Engineer tbpgr(てぃーびー) のブログ

Ruby | Module | protected_method_defined?

概要

Module#protected_method_defined?(name) -> bool

詳細

インスタンスメソッド name がモジュールに定義されており、 しかもその可視性が protected であるときに true を返却。
そうでなければ false を返却。

サンプルコード
require 'tbpgr_utils'

module Hogeable
  def hogeable
  end

  protected

  def protected_hogeable
  end
end

class Hoge
  include Hogeable
  def hoge
    print 'hoge'
  end

  protected

  def protected_hoge
  end
end

class ChildHoge < Hoge
end

bulk_puts_eval binding, <<-EOS
Hoge.protected_method_defined? :hogeable
Hoge.protected_method_defined? :protected_hogeable
Hoge.protected_method_defined? :hoge
Hoge.protected_method_defined? :protected_hoge
Hoge.protected_method_defined? 'protected_hoge'
ChildHoge.protected_method_defined? :protected_hogeable
ChildHoge.protected_method_defined? :protected_hoge
Hogeable.protected_method_defined? :protected_hogeable
EOS

__END__
下記はTbpgrUtils gemの機能
bulk_puts_eval

https://rubygems.org/gems/tbpgr_utils
https://github.com/tbpgr/tbpgr_utils

出力

出力

Hoge.protected_method_defined? :hogeable              # => false
Hoge.protected_method_defined? :protected_hogeable      # => true
Hoge.protected_method_defined? :hoge                  # => false
Hoge.protected_method_defined? :protected_hoge          # => true
Hoge.protected_method_defined? 'protected_hoge'         # => true
ChildHoge.protected_method_defined? :protected_hogeable # => true
ChildHoge.protected_method_defined? :protected_hoge     # => true
Hogeable.protected_method_defined? :protected_hogeable  # => true