value of such run-time assertions is limited,但他们确实有用。我已将它们并入YSupport
。在命令行中键入gem install y_support
,并按如下
require 'y_support/typing'
def foo x=nil, y=nil
x.aT; y.aT
# do stuff with x and y
end
助记符使用它:在0,a
的意思是“断言”和T
指TypeError
- 提高TypeError
如果断言失败。如果#aT
方法在没有参数的情况下被调用,它只是强制接收方必须是truey。如果提供了一个块,则可以写入任何断言。例如,下面的呼叫强制接收器由3整除:
6.aT { |n| n % 3 == 0 } #=> 6
7.aT { |n| n % 3 == 0 } #=> TypeError: 7:fixnum fails its check!
在检查所述方法参数的情况下,ArgumentError
是适当时,有的参数和类似的问题错误号码。当参数类型错误时,我更愿意提出TypeError
。可以使用两个字符串参数自定义#aT
方法的错误消息。第一个描述接收器,第二个描述块断言。例如:
7.aT "number of apples", "be divisible by three" do |n| n % 3 == 0 end
#=> TypeError: Number of apples fails to be divisible by three!
的#aT
方法,如果通过,返回其接收器,因此断言可以被链接:
81.aT("no. of apples", "divisible by 3) { |n|
n % 3 == 0
}.aT("no. of apples", "be a square") { |n|
root = n ** 0.5; root == root.floor
} ** 0.5 #=> 9.0
其它更专门的运行时断言是可用在YSupport
,如:
[ 1, 2, 3 ].aT_kind_of Enumerable #=> [ 1, 2, 3 ]
:foobar.aT_respond_to :each
#=> TypeError: Foobar:symbol does not respond to method 'each'!
:foobar.aT_respond_to :each, "object returned from the black box"
#=> TypeError: Object returned from the black box does not respond to method 'each'!
7.aT_equal 8
#=> TypeError: 7:fixnum must be equal to the prescribed value (8:fixnum)!
可以在YSupport
查找更多的这些方法自己,如果你错过了什么,欢迎您来贡献它。
作为邮政Scriptum这个职位,如果你习惯于ActiveSupport
的#present?
方法,YSupport
运行时断言它是:
[].aT_present "supplied array"
#=> TypeError: Supplied array not present!
如果'x'和'y' **必须**,则不要为它们提供默认值。易如反掌。 –
不幸的是,使用当前Ruby版本 – synapse
命名参数需要缺省值啊,忘记了。 –