module Test
def hello
puts "hello"
end
module Test2
def hello2
puts "hello2"
end
end
end
class Company
include Test
extend Test::Test2
end
c = Company.new
puts c.hello
puts Company.hello2
includedメソッドを使ったリファクタリングincludedメソッドは、includeメソッドによってモジュールが他のモジュールやクラスに
インクルードされたあとに呼び出されます。
引数にはモジュールをインクルードするクラスやモジュールが入ります。
このソースだとbaseにはCompanyが入っています。
module Test
def self.included(base)
base.extend(Test2)
end
def hello
puts "hello"
end
module Test2
def hello2
puts "hello2"
end
end
end
class Company
include Test
end
c = Company.new
puts c.hello
puts Company.hello2
active_supportを使ったリファクタリングmodule名をTest2からClassMethodsに変更しました。これがポイント
gem install 'active_support'
require 'active_support'
module Test
extend ActiveSupport::Concern
def hello
puts "hello"
end
module ClassMethods
def hello2
puts "hello2"
end
end
end
class Company
include Test
end
c = Company.new
puts c.hello
puts Company.hello2
0 件のコメント:
コメントを投稿