Class: Bmg::Ordering
- Inherits:
-
Object
- Object
- Bmg::Ordering
- Defined in:
- lib/bmg/support/ordering.rb
Instance Attribute Summary collapse
-
#attrs ⇒ Object
readonly
Returns the value of attribute attrs.
Instance Method Summary collapse
- #call(t1, t2) ⇒ Object
- #comparator ⇒ Object
- #compare_attrs(t1, t2) ⇒ Object
-
#initialize(attrs) ⇒ Ordering
constructor
A new instance of Ordering.
- #to_a ⇒ Object
Constructor Details
#initialize(attrs) ⇒ Ordering
Returns a new instance of Ordering.
4 5 6 7 8 9 10 11 12 |
# File 'lib/bmg/support/ordering.rb', line 4 def initialize(attrs) @attrs = if attrs.empty? [] elsif attrs.first.is_a?(Symbol) attrs.map{|a| [a, :asc] } else attrs end end |
Instance Attribute Details
#attrs ⇒ Object (readonly)
Returns the value of attribute attrs.
13 14 15 |
# File 'lib/bmg/support/ordering.rb', line 13 def attrs @attrs end |
Instance Method Details
#call(t1, t2) ⇒ Object
15 16 17 |
# File 'lib/bmg/support/ordering.rb', line 15 def call(t1, t2) comparator.call(t1, t2) end |
#comparator ⇒ Object
19 20 21 |
# File 'lib/bmg/support/ordering.rb', line 19 def comparator @comparator ||= ->(t1, t2) { compare_attrs(t1, t2) } end |
#compare_attrs(t1, t2) ⇒ Object
23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 |
# File 'lib/bmg/support/ordering.rb', line 23 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 |
#to_a ⇒ Object
42 43 44 |
# File 'lib/bmg/support/ordering.rb', line 42 def to_a attrs.to_a end |