【问题标题】:Scoped monkey-patching of a class范围猴子修补类
【发布时间】:2018-11-15 16:03:11
【问题描述】:

我需要修补一个类,但希望修补程序对某些模块是本地的。在 Ruby 中我会这样做:

module ArrayExtension
  refine Array do
    def ===(other)
      self.include?(other)
    end
  end
end

module Foo
  using ArrayExtension
  def self.foo
    case 2
    when [1,2] then puts "bingo!"
    end
  end
end

Foo.foo          # => bingo!
puts [1,2] === 2 # => false

Crystal 有类似的东西吗?

【问题讨论】:

  • Crystal 没有办法做到这一点,没有改进。

标签: scope crystal-lang refinements


【解决方案1】:

所以要重新定义===,你只需重新定义它。

module Foo
  def ===(other)
    self.includes?(other)
  end
end

class CustomArray(T) < Array(T)
  include Foo
end

custom_array = CustomArray(Int32).new

custom_array << 1
custom_array << 2

puts custom_array === 1 # true
puts custom_array === 2 # true
puts custom_array === 3 # false

【讨论】:

    猜你喜欢
    • 2016-10-30
    • 2011-04-25
    • 2014-03-05
    • 2012-10-13
    • 2012-03-13
    • 2013-12-26
    • 2012-06-14
    • 2012-03-29
    • 1970-01-01
    相关资源
    最近更新 更多