Is it possible to make an alias for a module in Ruby? Is it possible to make an alias for a module in Ruby? ruby ruby

Is it possible to make an alias for a module in Ruby?


Modules in Ruby aren't really that special, so you can just assign them to another constant:

[4] (pry) main: 0> module TestModule[4] (pry) main: 0*   def self.foo[4] (pry) main: 0*     "test"[4] (pry) main: 0*   end  [4] (pry) main: 0* end  => nil[5] (pry) main: 0> tm = TestModule=> TestModule[6] (pry) main: 0> tm.foo=> "test"


Michael's answer seems to solve your question... still, I read the question a bit differently and discovered something really nice that I thought worth sharing.

I understood your question as: "What do I do if I want to require two modules of the same name?", that is, how could I alias them if requiring both would result in a namespace clash? Because, as far as my understanding of Python's 'import ... as ...' goes, it also solves those kinds of problems. An example in Ruby:

#file a.rbmodule A  def self.greet    puts 'A'  endend#file b.rbmodule A  def self.greet    puts 'other A'  endend

Now if I would do this in a third file:

require_relative 'a'require_relative 'b'A.greet # => other A

the first A would be completely overridden by the A in b.rb. Using Michael's trick also won't help:

require_relative 'a'TMP_A = AA.greet # => ATMP_A.greet # => Arequire_relative 'b'TMP_A2 = AA.greet # => other ATMP_A2.greet # => other ATMP_A.greet # => other A :(

Too bad. Then I thought, well, in Ruby there's the ubiquitous dup for making a clone of basically everything and without too much hope I just typed this and reran the program:

require_relative 'a'TMP_A = A.dupA.greet # => ATMP_A.greet # => Arequire_relative 'b'TMP_A2 = AA.greet # => other ATMP_A2.greet # => other ATMP_A.greet # => A :P

That totally made my day, hope you guys appreciate it as much as well. Now that I think about it, it makes sense - a module is an object like any other after all, so why shouldn't dup work?