0
0

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 1 year has passed since last update.

[py2rb] wraps の2

Last updated at Posted at 2022-02-22

はじめに

移植やってます。
( from python 3.7 to ruby 2.7 )

wrap (Python)

以前の記事で、概ねwrapを表現できるようになりましたが、
moduleclass間ですと、NoMethodErrorになります。

失敗 (Ruby)

module M
  def my_decorator(meth)
    orig = method(meth)
    define_method(meth) do |*args, **kwargs|
      puts "Calling decorated method"
      orig.call(*args, **kwargs)
    end
  end  
end

class A
  include M

  def example
    def _example
      puts "Called decorated method"
    end
    my_decorator(:_example)
    _example    
  end
end

a = A.new
a.example

# output
undefined method `define_method'

ぐぬぬ。

しかし、Did you mean?さんがdefine_singleton_methodを教えてくれました。

成功 (Ruby)

module M
  def my_decorator(meth)
    orig = method(meth)
-    define_method(meth) do |*args, **kwargs|
+    define_singleton_method(meth) do |*args, **kwargs|
      puts "Calling decorated method"
      orig.call(*args, **kwargs)
    end
  end  
end

class A
  include M

  def example
    def _example
      puts "Called decorated method"
    end
    my_decorator(:_example)
    _example    
  end
end

a = A.new
a.example

# output
Calling decorated method
Called decorated method

分かりやすい記事

メモ

  • Python の wraps の2 を学習した
  • 百里を行く者は九十里を半ばとす
0
0
0

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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?