Sha256: 97d680ec3a47008919ce9181dde8af0a7e4293589079ca79a0adbfa5eda61f33

Contents?: true

Size: 767 Bytes

Versions: 13

Compression:

Stored size: 767 Bytes

Contents

module Bmg
  class Ordering

    def initialize(attrs)
      @attrs = attrs
    end
    attr_reader :attrs

    def call(t1, t2)
      comparator.call(t1, t2)
    end

    def comparator
      @comparator ||= ->(t1, t2) { compare_attrs(t1, t2) }
    end

    def compare_attrs(t1, t2)
      attrs.each do |(attr,direction)|
        a1, a2 = t1[attr], t2[attr]
        if a1.nil? && a2.nil?
          0
        elsif a1.nil?
          return direction == :desc ? -1 : 1
        elsif a2.nil?
          return direction == :desc ? 1 : -1
        elsif a1.respond_to?(:<=>)
          c = a1 <=> a2
          unless c.nil? || c==0
            return direction == :desc ? -c : c
          end
        end
      end
      0
    end

  end # class Ordering
end # module Bmg

Version data entries

13 entries across 13 versions & 1 rubygems

Version Path
bmg-0.21.2 lib/bmg/support/ordering.rb
bmg-0.21.0 lib/bmg/support/ordering.rb
bmg-0.20.4 lib/bmg/support/ordering.rb
bmg-0.20.2 lib/bmg/support/ordering.rb
bmg-0.20.1 lib/bmg/support/ordering.rb
bmg-0.20.0 lib/bmg/support/ordering.rb
bmg-0.19.2 lib/bmg/support/ordering.rb
bmg-0.19.1 lib/bmg/support/ordering.rb
bmg-0.19.0 lib/bmg/support/ordering.rb
bmg-0.18.15 lib/bmg/support/ordering.rb
bmg-0.18.14 lib/bmg/support/ordering.rb
bmg-0.18.13 lib/bmg/support/ordering.rb
bmg-0.18.12 lib/bmg/support/ordering.rb