following snippet is from rails code
def rescue_from(*klasses, &block)
options = klasses.extract_options!
unless options.has_key?(:with)
if blo开发者_运维知识库ck_given?
options[:with] = block
else
raise ArgumentError, "Need a handler. Supply an options hash that has a :with key as the last argument."
end
end
klasses.each do |klass|
key = if klass.is_a?(Class) && klass <= Exception
klass.name
elsif klass.is_a?(String)
klass
else
raise ArgumentError, "#{klass} is neither an Exception nor a String"
end
# put the new handler at the end because the list is read in reverse
self.rescue_handlers += [[key, options[:with]]]
end
end
end
Notice the operator <=
what is that?
See http://ruby-doc.org/core/classes/Module.html#M001669 for documentation on all the comparison operators exposed by Modules (and therefore Classes).
In this specific case: "Returns true if mod is a subclass of other or is the same as other. Returns nil if there‘s no relationship between the two. (Think of the relationship in terms of the class definition: "class A < B" implies "A < B")."
It's comparable to the is_a?
method which returns true if the receiver class is a subclass of the argument; consider:
Fixnum.superclass # => Integer
Fixnum <= Integer # => true
it's the operator for "LHS is an the same class as or Subclass of RHS". < is the operator for "LHS is a subclass of RHS."
This is wacky overloading of operators, but note that subclass declarations in Ruby also use < , as in
class SomeClass < ActiveRecord::Base
so at least it's consistent in that sense.
(LHS: left hand side, RHS: right hand side)
Pretty sure that means klass is a type of exception.
Typically though that means 'less than or equal to'. So that code could be saying if it's at least a class but not an exception...do something. But then the architecture of 'less than' would be out of place.
From the Code Documentation
# Handlers are inherited. They are searched from right to left, from
# bottom to top, and up the hierarchy. The handler of the first class for
# which exception.is_a?(klass) holds true is the one invoked, if any.
精彩评论