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.
- Where I should put the file related to the Ruby core extension of the
Moduleclass? Maybe in the Ruby on Railslibdirectory? - How should I properly “extend” the
Moduleclass in the core extension file? - Is it the right way to proceed? That is, for example, should I “extend” another class (
Object,BasicObject,Kernel, …) rather thanModule? 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?
You could use
define_singleton_methodto wrap your old method under a new name, like so:Answering your comment, you wouldn’t have to extend every single class by hand. The
define_singleton_methodis implemented in theObjectclass. So you could simply extend theObjectclass, so every class should have the method available…Put this in an initializer in your Rails app and you should be good to go…