Help us understand the problem. What is going on with this article?

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

More than 3 years have passed since last update.

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

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]

Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away