如何在模块内部写入常量?

时间:2011-08-04 09:26:21

标签: ruby-on-rails ruby constants

module Test1
  module Test2
    def self.included(base)
      # Where can I declare constant ? How ?
      base.extend ClassMethods
      base.class_eval do
           # named scopes
      end
    end
  end
end

class abc
  include Test1::Test2
end

我在哪里可以声明常数?怎么样?

2 个答案:

答案 0 :(得分:7)

我不确定我理解 - 你是说这个:

module Test1
  module Test2
    CONSTANT = 5
    def self.included(base)
      # Where can I declare constant ? How ?
      base.extend ClassMethods
      base.class_eval do
       # named scopes
      end
    end

    module ClassMethods
    end
  end
end

class A
  include Test1::Test2
end

puts A::CONSTANT # => 5

答案 1 :(得分:0)

在Ruby中,以大写字母开头的变量被视为常量。因此,您可以使用变量Pi = 3.14来声明常量值。