Ruby:引用常量时避免使用长嵌套模块

时间:2016-12-22 02:20:12

标签: ruby-on-rails ruby module constants

我有一个类在我的rails应用程序中定义一个常量。例如:

module A
 module B
   class C
     CONSTANT = "constant"
   end
 end
end

然后,在另一个模块中,我想让它保持不变:

module Test
  class Main
    def get_constant
       const = A::B::C::CONSTANT
    end
  end
end

这太长而且冗长。我尝试了一些不使用前缀A::B::C的方法。例如:

module Test
  class Main
    include A::B
    def get_constant
       const = C::CONSTANT
    end
  end
end

但在所有情况下,我总是遇到错误,因为我的rails app无法找到这个常数。请告诉我如何

1 个答案:

答案 0 :(得分:1)

在第二个类/模块中,您可以从第一个创建对常量的引用:

class One
  OneConst = 1
end

class Two
  TwoConst = One::OneConst
  def self.two_const
    TwoConst
  end
  def two_const
    TwoConst
  end
end

puts Two.two_const
puts Two.new.two_const
相关问题