Sha256: 6f552abf21eafadb9a5bf85119b3a8239cb6690e89501bed5e7e69d91fead0be

Contents?: true

Size: 1.01 KB

Versions: 10

Compression:

Stored size: 1.01 KB

Contents

module Comparable

  # Automatically generate comparitive definitions based on
  # attribute fields.
  #
  #   include Comparable[:a, :b]
  #
  # is equivalent to including a module containing:
  #
  #   def <=>(other)
  #     cmp = self.a <=> other.a; return cmp unless cmp == 0
  #     cmp = self.b <=> other.b; return cmp unless cmp == 0
  #     0
  #   end
  #
  def self.[](*accessors)
    Module.new do
      include Comparable
      define_method(:comparability){ accessors }
      define_method(:<=>) do |other|
        comparability.each do |a|
          cmp = (send(a) <=> other.send(a))
          break cmp unless cmp == 0
        end
      end
    end
  end

end

# Would it be nice if we could define comparability for all objects?
# Then Comparable[] method would not be needed. Just:
#
#   module Comparable
#
#    def <=>(other)
#      comparability.each do |field|
#        cmp = send(field) <=> other.send(field); return cmp unless cmp == 0
#      end
#    end
#
#  end
#
# But I fear it might break other code.

Version data entries

10 entries across 9 versions & 2 rubygems

Version Path
facets-glimmer-3.2.0 lib/core/facets/comparable/op_get.rb
facets-3.1.0 lib/core/facets/comparable/op_get.rb
facets-3.0.0 lib/core/facets/comparable/op_get.rb
facets-2.9.3 lib/core/facets/comparable/op_get.rb
facets-2.9.2 src/core/facets/comparable/op_get.rb
facets-2.9.2 lib/core/facets/comparable/op_get.rb
facets-2.9.1 lib/core/facets/comparable/op_get.rb
facets-2.9.0 lib/core/facets/comparable/op_get.rb
facets-2.9.0.pre.2 lib/core/facets/comparable/op_get.rb
facets-2.9.0.pre.1 lib/core/facets/comparable/op_get.rb