ActiveSupport::Concern 在 initialize 方法之前会运行 included 方法,而在 initialize 方法之后会运行 ClassMethods 方法。
下面是一个示例代码:
require 'active_support/concern'
module MyConcern
extend ActiveSupport::Concern
included do
puts "Running included method"
end
def initialize(*args)
super
puts "Running initialize method"
end
module ClassMethods
def class_method
puts "Running class method"
end
end
end
class MyClass
include MyConcern
def initialize(*args)
puts "Running MyClass initialize method"
super
end
end
MyClass.class_method
当你运行以上代码时,输出将会是:
Running included method
Running class method
Running MyClass initialize method
Running initialize method
可以看到,included 方法在 initialize 方法之前运行,而 ClassMethods 方法在 initialize 方法之后运行。