(In Ruby) allowing mixed-in class methods access to class constants

后端 未结 3 1472
星月不相逢
星月不相逢 2021-02-20 00:32

I have a class with a constant defined for it. I then have a class method defined that accesses that class constant. This works fine. An example:

#! /usr/bin/         


        
3条回答
  •  南笙
    南笙 (楼主)
    2021-02-20 00:41

    This seems to work:

    #! /usr/bin/env ruby
    
    module CommonMethods
        def shout_my_constant
            puts self::Const.upcase
        end
    end
    
    class NonInstantiableClass
        Const = "hello, world!"
        class << self
            include CommonMethods
        end
    end
    
    NonInstantiableClass.shout_my_constant
    

    HTH

提交回复
热议问题