How to "import" nested classes into the current class in Ruby?

In Ruby, I can embed modules / classes in other modules / classes. I want to add some declaration inside a file or class in order to be able to refer to nested classes by their short names, for example. use Inner to get Outer::Inner , as in Java, C #, etc. The syntax might look like this:

 module Outer class Inner; end class AnotherInner; end end class C import Outer: [:Inner, :AnotherInner] def f Inner end end 

The simplest implementation could be this:

 class Class def import(constants) @imported_constants = (@imported_constants || {}).merge Hash[ constants.flat_map { |namespace, names| [*names].map { |name| [name.to_sym, "#{namespace}::#{name}"] } }] end def const_missing(name) const_set name, eval(@imported_constants[name] || raise) end end 

Is there a solid implementation in Rails or some kind of gem that similarly imports, compatible with the Rails automatic loading mechanism?

+4
source share
1 answer
 module Outer class Inner; end class AnotherInner; end end class C include Outer def f Inner end end C.new.f # => Outer::Inner 

Remember: in Ruby there is no such thing as a nested class. A class is simply an object similar to any other object, and it is assigned to variables, like any other. In this particular case, a β€œvariable” is a constant that is named inside the module. And you add this constant to the namespace of another module (or class) in the same way as for any other constant: include module.

+2
source

All Articles