How do I use define_method to create class methods?

RubyMetaprogrammingClass Method

Ruby Problem Overview


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

def self.create_methods(method_name)
    # To create instance methods:
    define_method method_name do
      ...
    end

    # To create class methods that refer to the args on create_methods:
    ???
end

My answer to follow...

Ruby Solutions


Solution 1 - Ruby

I think in Ruby 1.9 you can do this:

class A
  define_singleton_method :loudly do |message|
    puts message.upcase
  end
end

A.loudly "my message"

# >> MY MESSAGE

Solution 2 - Ruby

I prefer using send to call define_method, and I also like to create a metaclass method to access the metaclass:

class Object
  def metaclass
    class << self
      self
    end
  end
end

class MyClass
  # Defines MyClass.my_method
  self.metaclass.send(:define_method, :my_method) do
    ...
  end
end

Solution 3 - Ruby

This is the simplest way in Ruby 1.8+:

class A
  class << self
    def method_name
      ...
    end
  end
end

Solution 4 - Ruby

To be used in Rails if you want to define class methods dynamically from concern:

module Concerns::Testable
  extend ActiveSupport::Concern

  included do 
    singleton_class.instance_eval do
      define_method(:test) do
        puts 'test'
      end
    end
  end
end

Solution 5 - Ruby

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).

Solution 6 - Ruby

You could also do something like this without relying on define_method:

A.class_eval do
  def self.class_method_name(param)
    puts param
  end
end

A.class_method_name("hello") # outputs "hello" and returns nil

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionChinasaurView Question on Stackoverflow
Solution 1 - RubyfguillenView Answer on Stackoverflow
Solution 2 - RubyVincent RobertView Answer on Stackoverflow
Solution 3 - RubyJoseph RavenwolfeView Answer on Stackoverflow
Solution 4 - RubyArturView Answer on Stackoverflow
Solution 5 - RubyChinasaurView Answer on Stackoverflow
Solution 6 - RubyBijanView Answer on Stackoverflow