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

馋奶兔 提交于 2019-12-04 02:12:55

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

Tooky

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 <module> is the better way to add those methods to the class.

The problem is, if you just write Const it is evaluated on Module creation time. You have to use Module#const_get instead like this: const_get(:Const). This is evaluated at runtime when the method is executed. So this happens in your class and not in your module.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!