How do I use define_method to create class methods?

前端 未结 6 1122
孤城傲影
孤城傲影 2020-11-30 20:34

This is useful if you are trying to create class methods metaprogramatically:

def self.create_methods(method_name)
    # To create instance methods:
    defi         


        
6条回答
  •  失恋的感觉
    2020-11-30 21:10

    Derived from: Jay and Why, who also provide ways to make this prettier.

    self.create_class_method(method_name)
      (class << self; self; end).instance_eval do
        define_method method_name do
          ...
        end
      end
    end
    

    Update: from VR's contribution below; a more concise method (as long as you're only defining one method this way) that is still standalone:

    self.create_class_method(method_name)
      (class << self; self; end).send(:define_method, method_name) do
        ...
      end
    end
    

    but note that using send() to access private methods like define_method() is not necessarily a good idea (my understanding is that it is going away in Ruby 1.9).

提交回复
热议问题