~ubuntu-branches/ubuntu/trusty/ruby-facets/trusty

« back to all changes in this revision

Viewing changes to lib/core/facets/comparable/op_get.rb

  • Committer: Package Import Robot
  • Author(s): Marc Dequènes (Duck)
  • Date: 2012-01-03 03:35:44 UTC
  • Revision ID: package-import@ubuntu.com-20120103033544-pq0yyio1675gfgw6
Tags: upstream-2.9.2
Import upstream version 2.9.2

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
module Comparable
 
2
 
 
3
  # Automatically generate comparitive definitions based on
 
4
  # attribute fields.
 
5
  #
 
6
  #   include Comparable[:a, :b]
 
7
  #
 
8
  # is equivalent to including a module containing:
 
9
  #
 
10
  #   def <=>(other)
 
11
  #     cmp = self.a <=> other.a; return cmp unless cmp == 0
 
12
  #     cmp = self.b <=> other.b; return cmp unless cmp == 0
 
13
  #     0
 
14
  #   end
 
15
  #
 
16
  def self.[](*accessors)
 
17
    Module.new do
 
18
      include Comparable
 
19
      define_method(:comparability){ accessors }
 
20
      define_method(:<=>) do |other|
 
21
        comparability.each do |a|
 
22
          cmp = (send(a) <=> other.send(a))
 
23
          break cmp unless cmp == 0
 
24
        end
 
25
      end
 
26
    end
 
27
  end
 
28
 
 
29
end
 
30
 
 
31
# Would it be nice if we could define comparability for all objects?
 
32
# Then Comparable[] method would not be needed. Just:
 
33
#
 
34
#   module Comparable
 
35
#
 
36
#    def <=>(other)
 
37
#      comparability.each do |field|
 
38
#        cmp = send(field) <=> other.send(field); return cmp unless cmp == 0
 
39
#      end
 
40
#    end
 
41
#
 
42
#  end
 
43
#
 
44
# But I fear it might break other code.
 
45