LoginSignup
6
5

More than 5 years have passed since last update.

rubyでインスタンスのメソッドを上書きする(もしくはwrapする)

Last updated at Posted at 2016-02-18

どこかで記事をみた気がしたが見つからなかったので一応メモ

class Sample
  def hello
    :hello
  end
end

sample = Sample.new
sample.hello # hello

# ここがミソ
sample.instance_eval { alias :original_hello :hello }
sample.define_singleton_method(:hello) { "wrapped #{original_hello}" }
# もしくは(コメントいただいて追記しました)
def sample.hello
  "wrapped #{super}"
end

sample.hello # wrapped hello

Sample.new.hello # hello

具体的にはrailsでcookiesがwriteされるときにフックして処理したかったが
うまい方法が思いつかなかったのでとりあえずこれで回避したという...
誰かうまい方法教えてください...

ruby 2.3.0p0 (2015-12-25 revision 53290) [x86_64-darwin14]

6
5
2

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
6
5