【问题标题】:How to use cattr_accessor in refinement [without rails]如何在细化中使用 cattr_accessor [无导轨]
【发布时间】:2013-11-03 17:15:55
【问题描述】:

我想在refinement类中使用active_support/core_ext/class/attribute_accessors中的cattr_accessor

  require 'active_support/core_ext/class/attribute_accessors'

  module ExtendedString
    refine String do
      cattr_accessor :separator
    end
  end

但我得到了错误:

 block in <module:ExtendedString>': undefined method `cattr_accessor' for #<refinement:String@Truncator::ExtendedString> (NoMethodError)

如何在类精炼中使用cattr_accessor

【问题讨论】:

    标签: ruby ruby-2.0 activesupport


    【解决方案1】:

    我会把它作为评论发布(因为它没有提供解决方案),但它需要格式化。

    回答失败的原因:

    促进cattr_accessor 的ActiveSupport 的core_ext.rb 是猴子修补核心对象Class,而ruby 文档则谈到了改进:

    ... 精炼块中的 self 是类似于 Module#module_eval 的匿名模块。

    因此,显然cattr_accessible 将无法从细化中访问。

    即使它会,cattr_accessible(准确地说是cattr_writercattr_reader)方法正在使用class_eval,这无论如何都会影响全局范围,这违背了改进的目的。

    【讨论】:

    • 所以改进没有为猴子补丁提供完整工具集? ;)
    • @freemanoid 是的,基本上。改进有一些(嗯,很多)限制,这是获得良好性能所必需的。但是,它是目前在某些范围内隔离“monkey-patches”的唯一选择,这对于在 gems 中使用“monkey-patches”至关重要。
    猜你喜欢
    • 2011-03-01
    • 1970-01-01
    • 2011-03-05
    • 1970-01-01
    • 2015-07-20
    • 2012-03-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多