发布时间: 2012-07-24 07:09:00
module RemovableConstants def def_if_not_defined(const, value) self.class.const_set(const, value) unless self.class.const_defined?(const) end def redef_without_warning(const, value) self.class.send(:remove_const, const) if self.class.const_defined?(const) self.class.const_set(const, value) end end
class A include RemovableConstants def initialize def_if_not_defined("Foo", "ABC") def_if_not_defined("Bar", "DEF") end def show_constants puts "Foo is #{Foo}" puts "Bar is #{Bar}" end def reload redef_without_warning("Foo", "GHI") redef_without_warning("Bar", "JKL") end end a = A.new a.show_constants a.reload a.show_constants
class Apple COLOR = "red" end puts Apple::COLOR puts "const_defined? #{Apple.const_defined?("COLOR")}" Apple.send(:remove_const, 'COLOR') # 三种不同的方法,都是定义常量 Apple.class_eval { COLOR = "yellow" } #class Apple; COLOR="yellow" ; end #Apple.const_set("COLOR", "green") puts Apple::COLOR