tags:

views:

152

answers:

4

following snippet is from rails code

  def rescue_from(*klasses, &block)
    options = klasses.extract_options!

    unless options.has_key?(:with)
      if block_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?

+1  A: 

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.

The Mirage
+2  A: 

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)

corprew
Why do you think it's "wacky overloading of operators"? The Inheritance Relationship imposes a partial ordering on classes, and in general, the symbol used to represent Relationships which impose partial orderings is `<=` (or rather `≤` but while that is a valid method name in Ruby, it's not a valid operator name). You are correct insofar as the usual operator for denoting a subtype relationship is `<:`, but that's neither a valid method nor operator name in Ruby, so I personally feel `<=` is good enough. It certainly beats the common abuse of using `+` for set union (which should be `∪`).
Jörg W Mittag
+2  A: 

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
maerics
+3  A: 

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")."

Greg Campbell