Skip to content

Instantly share code, notes, and snippets.

@okitan
Created July 20, 2011 00:18
Show Gist options
  • Save okitan/1094069 to your computer and use it in GitHub Desktop.
Save okitan/1094069 to your computer and use it in GitHub Desktop.
メタプログラミングRuby勉強会
class MyClass
def old_method
"my_method"
end
alias new_method old_method
# alias_method :new_method, :old_method
end
obj = MyClass.new
obj.old_method #=> "my_method"
obj.new_method #=> "my_method"
# アラウンドエイリアス
class MyClass
def old_method
warn "deprecated!"
new_method
end
end
obj = MyClass.new
obj.old_method #=> "my_method"
deprecated!
obj.new_method #=> "my_method"
# alias_method_chain pattern
class MyClass
def new_method_with_warning
warn "also deprecated!"
new_method_without_warning
end
alias new_method_without_warning new_method
alias new_method new_method_with_warning
# alias_method_chain :new_method, :warning
end
obj = MyClass.new
obj.new_method #=> "my_method"
also deprecated!
obj.new_method_with_warning #=> "my_method"
also deprecated!
obj.new_method_without_warning #=> "my_method"
module MyModule1
def my_method
"hello"
end
end
class MyClass0
class << self
include MyModule1
end
end
class MyClass1
extend MyModule1
end
# or ActiveSupport::Concern is easy
require 'active_support/concern'
module MyModule2
extend ActiveSupport::Concern
module ClassMethods
def my_method
"hello"
end
end
end
class MyClass2
include MyModule2
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment