13
15

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

クラスメソッドを alias_method_chain

Last updated at Posted at 2012-12-26

2017/11/22追記

Rails5からalias_method_chainは非推奨なので Module#prependを使いましょう。

メソッドをオーバーライドしたいけど元のメソッドを残したい時

ActiveSupport の alias_method_chain を使う。

class A
  def foo
    "foo"
  end
end

class B < A
  def foo_with_bar
    "foo bar"
  end
  alias_method_chain :foo, :bar
end

a = A.new
p a.foo              #=> "foo"

b = B.new
p b.foo              #=> "foo"
p b.foo_without_bar  #=> "foo bar"

alias_method_chain はインスタンスメソッド用なのでクラスメソッドに適用したい場合は以下のように記述する。

class A
  def self.foo
    "foo"
  end
end

class B < A
  class << self
    def foo_with_bar
      "foo bar"
    end
    alias_method_chain :foo, :bar
  end
end

p A.foo              #=> "foo"
p B.foo              #=> "foo"
p B.foo_without_bar  #=> "foo bar"
13
15
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
13
15

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?