Search code examples
ruby-on-railsrubymetaprogrammingextending

How to alias a class method within a module?


I am using Ruby v1.9.2 and the Ruby on Rails v3.2.2 gem. I had the following module

module MyModule
  extend ActiveSupport::Concern

  included do
    def self.my_method(arg1, arg2)
      ...
    end
  end
end

and I wanted to alias the class method my_method. So, I stated the following (not working) code:

module MyModule
  extend ActiveSupport::Concern

  included do
    def self.my_method(arg1, arg2)
      ...
    end

    # Note: the following code doesn't work (it raises "NameError: undefined
    # local variable or method `new_name' for #<Class:0x00000101412b00>").
    def self.alias_class_method(new_name, old_name)
      class << self
        alias_method new_name, old_name
      end
    end

    alias_class_method :my_new_method, :my_method
  end
end

In other words, I thought to extend the Module class someway in order to add an alias_class_method method available throughout MyModule. However, I would like to make it to work and to be available in all my Ruby on Rails application.

  1. Where I should put the file related to the Ruby core extension of the Module class? Maybe in the Ruby on Rails lib directory?
  2. How should I properly "extend" the Module class in the core extension file?
  3. Is it the right way to proceed? That is, for example, should I "extend" another class (Object, BasicObject, Kernel, ...) rather than Module? or, should I avoid implementing the mentioned core extension at all?

But, more important, is there a Ruby feature that makes what I am trying to accomplish so that I don't have to extend its classes?


Solution

  • You could use define_singleton_method to wrap your old method under a new name, like so:

    module MyModule
      def alias_class_method(new_name, old_name)
        define_singleton_method(new_name) { old_name }
      end
    end
    
    class MyClass
      def my_method
        puts "my method"
      end
    end
    
    MyClass.extend(MyModule)
    MyClass.alias_class_method(:my_new_method, :my_method)
    MyClass.my_new_method     # => "my method"
    

    Answering your comment, you wouldn't have to extend every single class by hand. The define_singleton_method is implemented in the Object class. So you could simply extend the Object class, so every class should have the method available...

    Object.extend(MyModule)
    

    Put this in an initializer in your Rails app and you should be good to go...