module Resort::Sortable::ClassMethods

Class methods to be used from the model class.

Public Instance Methods

first_in_order() click to toggle source

Returns the first element of the list.

@return [ActiveRecord::Base] the first element of the list.

# File lib/resort.rb, line 76
def first_in_order
  scoped.where(:first => true).first
end
last_in_order() click to toggle source

Returns the last element of the list.

@return [ActiveRecord::Base] the last element of the list.

# File lib/resort.rb, line 83
def last_in_order
  scoped.where(:next_id => nil).first
end
ordered() click to toggle source

Returns eager-loaded Components in order.

OPTIMIZE: Use IdentityMap when available @return [Array<ActiveRecord::Base>] the ordered elements

# File lib/resort.rb, line 92
def ordered
  ordered_elements = []
  elements = {}

  scoped.each do |element|
    if ordered_elements.empty? && element.first?
      ordered_elements << element
    else
      elements[element.id] = element
    end
  end

  raise "Multiple or no first items in the list where found. Consider defining a siblings method" if ordered_elements.length != 1 && elements.length > 0
  
  elements.length.times do
    ordered_elements << elements[ordered_elements.last.next_id]
  end
  ordered_elements.compact
end