When using class_eval in ruby, how to access a constant in the source class?

I want to extend the class using class_eval, and trying to access the constant from the source class, I got an error:

NameError: uninitialized constant HIS_CONSTANT from./my_module.rb:35:in `show_his_constant 'from (irb): 4

I tested a sample program and cannot make it work. Can someone check and see why this is not working? Thanks!

module MyModule puts "start my module" def mytest puts "mytest" end module YourModule def yourtest puts "yourtest" end end end module MyModule module YourModule module HisModule HIS_CONSTANT = 'THIS_IS_A_CONSTANT' end end end module MyModule module YourModule class HisClass include HisModule def show_constant puts HIS_CONSTANT end end end end MyModule::YourModule::HisClass.class_eval do def show_his_constant puts HIS_CONSTANT end end 

By the way, I know that this method may work:

 MyModule::YourModule::HisClass.class_eval do def show_his_constant puts MyModule::YourModule::HisModule::HIS_CONSTANT end end 

But I do not want to use the namespace for access, as it should already be included.

+4
source share
2 answers

You should use ruby ​​1.8, as your code works as written in version 1.9.

In 1.8, the problem is that the constant is related to the block definition context (regardless of self , when you started writing MyModule::YourModule::HisClass.class_eval ). You can defer persistent binding until self becomes an instance of MyModule::YourModule::HisClass using Module.const_get .

 MyModule::YourModule::HisClass.class_eval do def show_his_constant puts self.class.const_get(:HIS_CONSTANT) end end irb 1.8.7> MyModule::YourModule::HisClass.new.show_his_constant THIS_IS_A_CONSTANT 
+4
source

How about this

 MyModule::YourModule::HisClass.class_eval do def show_his_constant puts self::class::HIS_CONSTANT end end 
0
source

Source: https://habr.com/ru/post/1441257/


All Articles