0

I have a file SomethingClass.rb which looks as follows:

class SomethingClass
  def initialize
    puts "Hello World"
  end
end

I would like to require the file SomethingClass.rb, and make SomethingClass part of the module SomethingModule without changing the file.

Also, I would like to avoid making SomethingClass part of the namespace outside of that module at all. In other words, I want to require the file and the rest of my application should not change apart from the fact that SomethingModule will be defined.

This does not work (I assume because require is executed in Kernel scope):

module SomethingModule
  require './SomethingClass.rb'
end

Is this possible in Ruby?

PawkyPenguin
  • 219
  • 2
  • 9
  • 2
    Unless I've misunderstood the question, this doesn't seem to have anything do with a file containing a class definition being required in another file. Suppose you have one file that defines one class and one module (not a class within the module). I believe you wish to move the class to within the module without changing the class definition. Is that correct? If so, is that the essence of the question? – Cary Swoveland Sep 30 '17 at 22:27
  • @CarySwoveland Yes, that is correct. I asked the question with `require` because this is the way I intended to use it in. I wasn't sure whether the use of `require` could make solutions possible other than moving a class to a module. – PawkyPenguin Oct 01 '17 at 03:30

1 Answers1

1

Without changing your class file, from what I've gathered, there are only kind of hacky ways to do this - see Load Ruby gem into a user-defined namespace and How to undefine class in Ruby?.

However I think if you allow yourself to modify the class file, it is a little easier. Probably the simplest thing to do would be to set the original class name to something that will surely have no name conflict, e.g.:

class PrivateSomethingClass
  def initialize
    puts "Hello World"
  end
end

module SomethingModule
  SomethingClass = PrivateSomethingClass
end

Now you have SomethingModule::SomethingClass defined but not SomethingClass on the global namespace.

Another way to do it would be to use a factory method and anonymous class:

class SomethingClassFactory
  def self.build
    Class.new do
      def initialize
        "hello world"
      end
    end
  end
end

module SomethingModule
  SomethingClass = SomethingClassFactory.build
end
max pleaner
  • 26,189
  • 9
  • 66
  • 118