Class: Bmg::Ordering

Inherits:
Object
  • Object
show all
Defined in:
lib/bmg/support/ordering.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(attrs) ⇒ Ordering

Returns a new instance of Ordering.



4
5
6
# File 'lib/bmg/support/ordering.rb', line 4

def initialize(attrs)
  @attrs = attrs
end

Instance Attribute Details

#attrsObject (readonly)

Returns the value of attribute attrs.



7
8
9
# File 'lib/bmg/support/ordering.rb', line 7

def attrs
  @attrs
end

Instance Method Details

#call(t1, t2) ⇒ Object



9
10
11
# File 'lib/bmg/support/ordering.rb', line 9

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

#comparatorObject



13
14
15
# File 'lib/bmg/support/ordering.rb', line 13

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

#compare_attrs(t1, t2) ⇒ Object



17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
# File 'lib/bmg/support/ordering.rb', line 17

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