Skip to content

Instantly share code, notes, and snippets.

@murayama
Created July 9, 2013 01:50
Show Gist options
  • Save murayama/5954033 to your computer and use it in GitHub Desktop.
Save murayama/5954033 to your computer and use it in GitHub Desktop.
rubyでモジュールを作るときの賢いやり方
# -*- coding: utf-8 -*-
module SomeModule
def self.included(klass)
klass.send(:include, SomeModule::Methods)
klass.send(:extend, SomeModule::ClassMethods)
end
module Methods
def foo
p 'foo'
end
end
module ClassMethods
def bar
p 'bar'
end
end
end
class MyClass
include SomeModule
end
my = MyClass.new
my.foo #=> foo
my.bar #=> error
MyClass.foo #=> error
MyClass.bar #=> bar

rubyのモジュールの賢い実装の仕方

あるクラスにインスタンスメソッドとクラスメソッドをそれぞれ追加したい場合に、
一つのモジュールをincludeするだけで、両方を追加するようにできる

※includeとextendの違いについては割愛

ポイントは、

  def self.included(klass)
    klass.send(:include, SomeModule::Methods)
    klass.send(:extend, SomeModule::ClassMethods)
  end 

includedはモジュールがインクルードされた時にコールされるメソッド
引数にインクルードしたクラスが渡ってくるので、そこでincludeとextendを実行してやる

ActiveSupport::Concern を使うと同じ事がもっときれいにかける?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment