Created
August 23, 2011 16:11
-
-
Save Evangenieur/1165694 to your computer and use it in GitHub Desktop.
Resolve CONSTANT in instance_eval & Import CONSTANT from Module / Class
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
module GlobalConstant | |
AUTORESOLVE = [] | |
AUTOIMPORT = [] | |
def self.install | |
Object.instance_eval do | |
class << self | |
alias old_const_missing const_missing | |
def const_missing constant | |
to_check = GlobalConstant::AUTORESOLVE.keep_if { |m| m.singleton_class == self } + GlobalConstant::AUTOIMPORT | |
to_check.each do |m| | |
return m.const_get constant if m.const_defined? constant | |
end | |
old_const_missing constant | |
end | |
end | |
end | |
end | |
end |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
> irb -r ./global_constant.rb -r ./test.rb | |
####### BEFORE ########## | |
>> Test::ITMORE | |
=> "good" | |
>> Test.run { ITMORE } | |
NameError: uninitialized constant Module::ITMORE | |
######## INSTALL ############## | |
>> GlobalConstant.install | |
>> GlobalConstant::AUTORESOLVE << Test | |
=> [Test] | |
>> Test.run { ITMORE } | |
=> "good" | |
>> GlobalConstant::AUTOIMPORT << Test | |
=> [Test] | |
>> ITMORE | |
=> "good" |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
module Test | |
ITMORE = "good" | |
def self.run &block | |
instance_eval &block if block_given? | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment