class 的范围猴子修补
Scoped monkey-patching of a class
我需要修补 class,但希望修补程序是某些模块的本地修补程序。在 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中有类似的东西吗?
所以要重新定义 ===
你只需重新定义它即可。
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
我需要修补 class,但希望修补程序是某些模块的本地修补程序。在 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中有类似的东西吗?
所以要重新定义 ===
你只需重新定义它即可。
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