(在Ruby中)允许混合类方法访问类常量 [英] (In Ruby) allowing mixed-in class methods access to class constants

查看:109
本文介绍了(在Ruby中)允许混合类方法访问类常量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个类定义了一个常量。然后我有一个类方法定义访问该类常量。这工作正常。示例:

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/env ruby

class NonInstantiableClass
    Const = "hello, world!"
    class << self
        def shout_my_constant
            puts Const.upcase
            end
        end
    end

NonInstantiableClass.shout_my_constant

我的问题出现在尝试将这个类方法移出到外部模块,如下:

My problem arises in attempting to move this class method out to an external module, like so:

#! /usr/bin/env ruby

module CommonMethods
    def shout_my_constant
        puts Const.upcase
        end
    end

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

NonInstantiableClass.shout_my_constant

Ruby将该方法解释为从模块请求常量,而不是类:

Ruby interprets the method as requesting a constant from the module, rather than the class:

line 5:in `shout_my_constant': uninitialized constant CommonMethods::Const (NameError)

你的家伙们必须让方法访问类常量吗?非常感谢。

So, what magic tricks do you fellows have to let the method access the class constant? Many thanks.

推荐答案

这似乎有效:

#! /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

这篇关于(在Ruby中)允许混合类方法访问类常量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆