2014-09-30 76 views
6

在ActiveSupport :: Concern上下文中访问包含类的受保护常量的最简单方法是什么?在ActiveSupport中访问包含类的受保护常量::关注

实例类:

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 

但是,它不感觉不错。 :-)

有什么更好的建议?

+2

你的问题是我的答案。虽然我同意它感觉不对,但你的问题最终给了我一个解决方案,至少工作。 – 2014-12-25 21:14:44

回答

0

从关注点访问包含类的常量并不是一个好主意。

一个关注不应该有它包含在类(太多)知识

我会去为一个共同的API在关注并在必要时覆盖......这样的:

​​
+1

你会有一个方法的恶性通货膨胀的顺序(包括类的数量)x(使用常量的方法的数量):) – 2015-12-30 22:35:49

5

首先,你应该把#print_constantincluded块:

module Printable 
    extend ActiveSupport::Concern 

    included do 
    private 

    def print_constant 
     puts MY_CONSTANT 
    end 
    end 
end 

现在有访问类constan至少两种方式吨MY_CONSTANT

  1. #included产量与base参数类似于Ruby的 #included

    module Printable 
        extend ActiveSupport::Concern 
    
        included do |base| 
        private 
    
        define_method :print_constant do 
         puts base::MY_CONSTANT 
        end 
        end 
    end 
    
  2. 另一种方法是从self.class打算:

    module Printable 
        extend ActiveSupport::Concern 
    
        included do 
        private 
    
        def print_constant 
         puts self.class::MY_CONSTANT 
        end 
        end 
    end 
    

ActiveSupport Concern Documentation