在 ActiveSupport::Concern 上下文中访问包含类的 protected 常量的最简单方法是什么?
示例类:
module Printable
extend ActiveSupport::Concern
private
def print_constant
puts MY_CONSTANT
end
end
class Printer
include Printable
def print
print_constant
end
private
MY_CONSTANT = 'Hello'.freeze
end
此解决方案产生错误:
NameError: uninitialized constant Printable::MY_CONSTANT
我知道一个似乎可行的替代方案:
puts self.class::MY_CONSTANT
但是,感觉不对。 :-)
有更好的建议吗?
最佳答案
首先,您应该将#print_constant
放入included
block 中:
module Printable
extend ActiveSupport::Concern
included do
private
def print_constant
puts MY_CONSTANT
end
end
end
现在至少有两种方法可以访问类常量MY_CONSTANT
:
#included
产生一个类似于 Ruby 的base
参数#included
:module Printable extend ActiveSupport::Concern included do |base| private define_method :print_constant do puts base::MY_CONSTANT end end end
另一个方法来自
self.class
:module Printable extend ActiveSupport::Concern included do private def print_constant puts self.class::MY_CONSTANT end end end
关于ruby-on-rails - 在 ActiveSupport::Concern 中访问包含类的 protected 常量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26120791/