ruby-on-rails - 在 ActiveSupport::Concern 中访问包含类的 protected 常量

标签 ruby-on-rails ruby model separation-of-concerns

在 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:

  1. #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
    
  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

关于ruby-on-rails - 在 ActiveSupport::Concern 中访问包含类的 protected 常量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26120791/

相关文章:

ruby-on-rails - 不确定在哪里(模型或 Controller )定义我的查找方法

arrays - 如何在 Active Admin Rails 4 中保存数组?

ruby-on-rails - 为什么 ENV ["HOME"] nil 在我的 rake 任务中?

mysql - 链接一个where查询?

arrays - 要散列的 Ruby 字符串数组

ruby - Mac + Ruby : Can't access ioctl of Socket? 如何修复?

ruby - Ruby 中的双点符号

mysql - 事件记录 - destroy_all 并在事务中创建

ruby-on-rails - 如何在 Heroku 上使用 Rails 3.2.2 实现 SPDY?

javascript - 如何在 Three.js 中处理动画模型?