Qiita Teams that are logged in
You are not logged in to any team

Log in to Qiita Team
Community
OrganizationEventAdvent CalendarQiitadon (β)
Service
Qiita JobsQiita ZineQiita Blog
4
Help us understand the problem. What are the problem?

More than 5 years have passed since last update.

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

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

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
4
Help us understand the problem. What are the problem?