File: compare_on.rb

package info (click to toggle)
ruby-facets 2.9.2-1
  • links: PTS, VCS
  • area: main
  • in suites: wheezy
  • size: 9,824 kB
  • sloc: ruby: 25,483; xml: 90; makefile: 20
file content (35 lines) | stat: -rw-r--r-- 752 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
class Module

  # Automatically generate sorting definitions based on attribute fields.
  #
  #   sort_on :a, :b
  #
  # _is equivalent to_
  #
  #   def <=>(o)
  #     cmp = self.a <=> o.a; return cmp unless cmp == 0
  #     cmp = self.b <=> o.b; return cmp unless cmp == 0
  #     0
  #   end
  #
  # TO BE DEPRECATED

  def compare_on(*fields)
    code = %{def <=>(o)\n}
    fields.each { |f|
      code << %{cmp = ( @#{f} <=> o.instance_variable_get('@#{f}') );
                return cmp unless cmp == 0\n}
    }
    code << %{0\nend; alias_method :cmp, :<=>;}
    class_eval( code )
    fields
  end

  # Should this be a standard alias?
  alias_method :sort_on, :compare_on

  # Deprecated usage
  #alias_method :sort_attributes, :sort_on

end