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?
source share