How to redefine a Ruby constant without warning?

后端 未结 4 1551
眼角桃花
眼角桃花 2020-12-23 15:57

I\'m running some Ruby code which evals a Ruby file every time its date changes. In the file, I have constant definitions, like

Tau = 2 * Pi
<
4条回答
  •  既然无缘
    2020-12-23 16:47

    The following module may do what you want. If not it may provide some pointers to your solution

    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
    

    And as an example of using it

    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
    

    Gives the following output

    Foo is ABC
    Bar is DEF
    Foo is GHI
    Bar is JKL
    

    Forgive me if i've broken any ruby taboos here as I am still getting my head around some of the Module:Class:Eigenclass structure within Ruby

提交回复
热议问题