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

后端 未结 3 1497
星月不相逢
星月不相逢 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:36

    Its probably worth noting that you don't need to include modules into a metaclass.

    class NonInstantiableClass
        Const = "hello, world!"
        class << self
            include CommonMethods
        end
    end
    

    Ruby has the extend keyword that effectively adds the modules interface to a class, e.g.

    class NonInstantiableClass
        Const = "hello, world!"
        extend CommonMethods
    end
    

    You still need to ensure you're referencing the right constant using self::Const or const_get, but extend is the better way to add those methods to the class.

提交回复
热议问题