LoginSignup
6
4

More than 5 years have passed since last update.

Ruby - includeして使うモジュールの中でdefine_methodする

Last updated at Posted at 2015-02-10

モジュールにattr_accessorのような、動的にメソッドを定義する機能を持たせたい時の書き方でハマったのでメモしておきます。

通常なら、クラスメソッドを定義したClassMethodsというサブモジュールを作成して、include元のクラスに継承させるのですが、これだとdefine_methodClassMethodsのコンテキストで呼ばれるため、include元のクラスにはメソッドが定義されません。

module Hoge
  def self.included(base)
    base.extend(ClassMethods)
  end

  module ClassMethods
    def my_define_method(name)
      define_method(name) do
        # ...
      end
    end
  end
end

class_evalを使って、include元のクラスコンテキストの中でdefine_methodを呼んだらうまく行きました。

module Hoge
  def self.included(base)
    base.class_eval do
      def self.my_define_method(name)
        define_method(name) do
          # ...
        end
      end
    end
  end
end
class Fuga
  include Hoge
  my_define_method :my_method
end

fuga = Fuga.new
fuga.my_method
6
4
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
6
4