Question

Given this code

module A::Internal
  def self.generate_method(name, args)
     A.instance_eval do
        unless self.respond_to? :"#{name}"
           define_method :"#{name}" do
              return true
           end
        end
     end
  end
end

Is there a better way to refer to A in A.instance_eval do? I want to place the method generate_method on a sublevel (not in the class A itself). Is there a way to refer to A differently from within Intenal?

The method genrate_method is on the class level as the genrated method will be on the self level. But for consistency sakes and for a bunch of constant/method, I want to define them in a submodule to avoid collision betwen generated methods for A and defined methods.

Was it helpful?

Solution

You can do

module A
  module Internal
    Module.nesting[1] # => A
  end
end

A tricky thing about this is that you have to explicitly nest the modules. If you do

module A::Internal
  Module.nesting[1]
end

then it will not work.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top