Ruby:如何从类中访问常量模块包含在

时间:2016-04-27 15:11:07

标签: ruby-on-rails ruby

我正在尝试访问我在其中包含的模块中的各个类中保持的常量。作为一个基本的例子

module foo
  def do_something_to_const
    CONSTANT.each { ... do_something ... }
  end
end

class bar
  include foo

  CONSTANT = %w(I want to be able to access this in foo)
end

class baz
  include foo

  CONSTANT = %w(A different constant to access)
end

由于模块的逻辑在多个类之间共享,我希望能够仅引用常量(其名称在每个类中保持相同,但内容不同)。我该怎么做呢?

3 个答案:

答案 0 :(得分:5)

您可以将所包含的类模块引用为self.class,使用const_get或仅self.class::CONST,后者稍快一些:

module M
  def foo
    self.class::CONST
  end
end

class A
  CONST = "AAAA"
  include M
end

class B
  CONST = "BBBB"
  include M
end

puts A.new.foo # => AAAA
puts B.new.foo # => BBBB

答案 1 :(得分:1)

您可以使用self.class

引用该课程
module Foo
  def do_something
    self.class::Constant.each {|x| puts x}
  end
end

class Bar
  include Foo
  Constant = %w(Now is the time for all good men)
end

class Baz
  include Foo
  Constant = %w(to come to the aid of their country)
end

bar = Bar.new
bar.do_something
=>
Now
is
the
time
for
all
good
men
 => ["Now", "is", "the", "time", "for", "all", "good", "men"] 

baz = Baz.new
baz.do_something
=>
to
come
to
the
aid
of
their
country
 => ["to", "come", "to", "the", "aid", "of", "their", "country"]

答案 2 :(得分:0)

您可以使用::运算符将CONSTANT范围限定为BAR类。语法看起来像这样:

module Foo
  def do_something_to_const
    Bar::CONSTANT.each { |item| puts item }
  end
end

class Bar
  include Foo

  CONSTANT = %w(I want to be able to access this in foo)
end

Bar.new.do_something_to_const # outputs each item in Bar::CONSTANT
但是,我试图避免这种情况。包含的模块不需要知道要包含它的类的实现细节。