您可以执行以下操作,尽管我希望有一些宝石可以做到这一点,并且做得更好:
module ArgCheck
def type_check(label, arg, klass)
raise_arg_err label + \
" (= #{arg}) is a #{arg.class} object, but should be be a #{klass} object" unless arg.is_a? klass
end
def range_check(label, val, min, max)
raise_arg_err label + " (= #{val}) must be between #{min} and #{max}" unless val >= min && val <= max
end
def min_check(label, val, min)
puts "val = #{val}, min = #{min}"
raise_arg_err label + " (= #{val}) must be >= #{min}" unless val >= min
end
def max_check(val, min)
raise_arg_err label + " (= #{val}) must be <= #{max}" unless val <= max
end
# Possibly other checks here
private
def raise_arg_err(msg)
raise ArgumentError, msg + "\n backtrace: #{caller_locations}"
end
end
class Product
include ArgCheck
attr_accessor :quantity, :type, :price, :imported
def initialize(quantity, type, price)
# Check arguments
min_check 'quantity', quantity, 0
type_check 'type', type, String
type_check 'price', price, Float
@quantity = quantity
@type = type
@price = price.round(2)
end
end
product = Product.new(-1, :cat, 3)
# => arg_check.rb:23:in `raise_arg_err': quantity (= -1) must be >= 0 (ArgumentError)
# backtrace: ["arg_check.rb:11:in `min_check'", "arg_check.rb:33:in `initialize'", \
# "arg_check.rb:43:in `new'", "arg_check.rb:43:in `<main>'"]
product = Product.new(1, :cat, 3)
# => arg_check.rb:26:in `raise_arg_err': type (= cat) is a Symbol object, \
# but should be be a String object (ArgumentError)
# backtrace: ["arg_check.rb:3:in `type_check'", "arg_check.rb:34:in `initialize'", \
# "arg_check.rb:48:in `new'", "arg_check.rb:48:in `<main>'"]
product = Product.new(1, "cat", 3)
# => arg_check.rb:23:in `raise_arg_err': price (= 3) must be a Float object (ArgumentError)
# backtrace: ["arg_check.rb:3:in `type_check'", "arg_check.rb:35:in `initialize'", \
# "arg_check.rb:53:in `new'", "arg_check.rb:53:in `<main>'"]
product = Product.new(1, "cat", 3.00) # No exception raised
请注意,在 irb 中运行时,Kernel#caller_locations
会带来很多您不想要的东西,而从命令行运行时您不会得到这些东西。