From: Phrogz Date: 2006-02-27T03:18:35+09:00 Subject: Re: Scope of constants in instance_eval For those interested in doing the same, I've hacked up a quick method for promoting the constants of a class/module to the main Object scope, and then restoring the original values. You can: * Automatically promote all constants of the class/module * Promote only specific constants * Choose to explicitly restore the constants or * Supply a block that will be yielded to before the constants are automatically restored class Module # Push the constants of this class/module up to global space # saving any original values in Object for later restoration # # If no names are supplied, all constants in this class/module # are promoted. # # If a block is supplied, it will be yielded to before automatically # restoring the global scope to its pristine state. def promote_constants( *const_names ) const_names.flatten! const_names = self.constants if const_names.empty? @_original_constant_values = {} const_names.each { |name| if self.const_defined?( name ) if Object.const_defined?( name ) @_original_constant_values[ name ] = Object.const_get( name ) end Object.const_set( name, self.const_get( name ) ) else warn "Cannot promote non-existent constant '#{name}'" end } if block_given? yield restore_constants end end # Restore Object's constants to undo the effects of #promote_constants def restore_constants( *const_names ) return unless @_original_constant_values const_names.flatten! const_names = self.constants if const_names.empty? const_names.each { |name| if val=@_original_constant_values[ name ] Object.const_set( name, val ) else Object.instance_eval{ remove_const( name ) } end } @_original_constant_values = nil end end