Sha256: 4c26d2e33d50e972d889ae22bd121ab6d5fc0dca2f6b3b2c83f5beb1ff9f55e3

Contents?: true

Size: 1.46 KB

Versions: 26

Compression:

Stored size: 1.46 KB

Contents

#--
# NOTE Better as a parameterized mixin?
#++

class Module

  # Automatically generate sorting defintions base 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
  #
  def sort_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 :compare_on, :sort_on

  # Deprecated usage
  alias_method :sort_attributes, :sort_on

end


#  _____         _
# |_   _|__  ___| |_
#   | |/ _ \/ __| __|
#   | |  __/\__ \ |_
#   |_|\___||___/\__|
#
=begin test

  require 'test/unit'

  class TCModule < Test::Unit::TestCase

    def test_sort_on
      c = Class.new
      c.class_eval {
        def initialize(a,b)
          @a=a; @b=b
        end
        sort_on :a,:b
      }
      a = [c.new(10,20),c.new(10,30)]
      assert_equal( a, a.sort )
      a = [c.new(10,30),c.new(10,20)]
      assert_equal( a.reverse, a.sort )
      a = [c.new(10,10),c.new(20,10)]
      assert_equal( a, a.sort )
      a = [c.new(20,10),c.new(10,10)]
      assert_equal( a.reverse, a.sort )
      a = [c.new(10,30),c.new(20,10)]
      assert_equal( a, a.sort )
    end

  end

=end

Version data entries

26 entries across 26 versions & 1 rubygems

Version Path
facets-1.0.0 lib/facet/module/sort_on.rb
facets-0.9.0 lib/nano/module/sort_on.rb
facets-1.0.3 packages/core/lib/facet/module/sort_on.rb
facets-1.1.0 lib/facet/module/sort_on.rb
facets-1.2.0 lib/facets/core/module/sort_on.rb
facets-1.3.0 lib/facets/core/module/sort_on.rb
facets-1.2.1 lib/facets/core/module/sort_on.rb
facets-1.3.2 lib/facets/core/module/sort_on.rb
facets-1.3.1 lib/facets/core/module/sort_on.rb
facets-1.3.3 lib/facets/core/module/sort_on.rb
facets-1.4.0 lib/facets/core/module/sort_on.rb
facets-1.4.2 lib/facets/core/module/sort_on.rb
facets-1.4.1 lib/facets/core/module/sort_on.rb
facets-1.4.3 lib/facets/core/module/sort_on.rb
facets-1.4.5 lib/facets/core/module/sort_on.rb
facets-1.4.4 lib/facets/core/module/sort_on.rb
facets-1.7.30 lib/facets/core/module/sort_on.rb
facets-1.7.38 lib/facets/core/module/sort_on.rb
facets-1.7.0 lib/facets/core/module/sort_on.rb
facets-1.7.46 lib/facets/core/module/sort_on.rb