Skip to content

Instantly share code, notes, and snippets.

@Evangenieur
Created August 23, 2011 16:11
Show Gist options
  • Save Evangenieur/1165694 to your computer and use it in GitHub Desktop.
Save Evangenieur/1165694 to your computer and use it in GitHub Desktop.
Resolve CONSTANT in instance_eval & Import CONSTANT from Module / Class
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
> 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"
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