module IncludedCount
class << self
def included(klass)
@included ||= []
@included << klass
end
def included_module_and_class
@included
end
def included_count
@included&.count || 0
end
end
end
p IncludedCount.included_count
class IncludeClass1
include IncludedCount
end
class IncludeClass2
include IncludedCount
end
class IncludeClass3
include IncludedCount
end
p IncludedCount.included_count
IncludedCount.included_module_and_class
0 3
[IncludeClass1, IncludeClass2, IncludeClass3]
class InheritedTiming
class << self
private
def inherited(subclass)
p subclass.ancestors
p subclass.instance_methods.include? :super_method
p subclass.instance_methods.include? :subclass_method
end
end
def super_method
end
end
puts "クラス定義式の前"
class InheritedTimingSubClass < InheritedTiming
puts "クラス定義式の後"
def subclass_method
end
end
p InheritedTimingSubClass.instance_methods.include? :super_method
InheritedTimingSubClass.instance_methods.include? :subclass_method
クラス定義式の前 [InheritedTimingSubClass, InheritedTiming, Object, JSON::Ext::Generator::GeneratorMethods::Object, Kernel, BasicObject] true false クラス定義式の後 true
true
■メソッドが追加されたら処理をしたい
class AddedMethodClass
def before_added_method; end
class << self
private
def method_added(method_name)
puts "method added: #{method_name}"
end
end
def after_added_method; end
define_method :add_from_define_method, ->(){}
end
AddedMethodClass.class_eval do
def add_from_class_eval; end
end
method added: after_added_method method added: add_from_define_method method added: add_from_class_eval
:add_from_class_eval
class BrokenMethodClass
class << self
private
def method_added(method_name)
raise "Wow!"
end
end
def after_added_method
puts "succeeded"
end
rescue
puts "rescued"
end
BrokenMethodClass.new.after_added_method
rescued succeeded
method_added
はメソッド定義の後に実行される
第一部完! 次回以降は Part4 から読みたい節をピックアップして読む