1
0

More than 1 year has passed since last update.

module の include と extend

Last updated at Posted at 2022-02-22

はじめに

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

wrap (Python)

前回の記事(moduleclass間)でホッとしたのですが、modulemodule間ですと、NoMethodErrorになります。

失敗 (Ruby)

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

module A
  include M
  module_function

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

a = A
a.example

# output
undefined method `define_method'

ぐぬぬ。

成功 (Ruby)

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

module A
-  include M
+  extend M
  module_function

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

a = A
a.example

# output
Calling decorated method
Called decorated method

Module#include は、クラス(のインスタンス)に機能を追加しますが、extend は、ある特定のオブジェクトだけにモジュールの機能を追加したいときに使用します。

ふむふむ、Moduleはインスタンスが生成されないのでincludeでは追加されないと理解。

メモ

  • Ruby の extend を学習した
  • 百里を行く者は九十里を半ばとす
1
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
1
0