class RankleIndex

Public Class Methods

position(instance, name) click to toggle source
# File lib/rankle_index.rb, line 40
def self.position instance, name
  indexable_position = where(indexable_name: name.to_s, indexable_id: instance.id, indexable_type: instance.class.to_s).first_or_create!.indexable_position
  indexable_scope = where(indexable_name: name.to_s)
  indexable_scope = indexable_scope.where(indexable_type: instance.class.to_s) if name == :default
  indexable_scope = indexable_scope.where('indexable_position < ?', indexable_position)
  indexable_scope.count
end
rank(instance, name, position) click to toggle source
# File lib/rankle_index.rb, line 28
def self.rank instance, name, position
  existing_indices = if name == :default
                          RankleIndex.where indexable_name: name.to_s, indexable_type: instance.class.to_s
                        else
                          RankleIndex.where indexable_name: name.to_s
                        end
  position = existing_indices.count - 1 if position > existing_indices.count
  position = 0 if position < 0
  index = RankleIndex.where(indexable_name: name.to_s, indexable_id: instance.id, indexable_type: instance.class.to_s).first_or_create!
  index.update_attribute(:row_order_position, position)
end
ranked(name) click to toggle source
# File lib/rankle_index.rb, line 48
def self.ranked name
  where(indexable_name: name).order(:indexable_position).map do |duck|
    duck.indexable_type.classify.constantize.find(duck.indexable_id)
  end
end
ranks(klass, ranker) click to toggle source
# File lib/rankle_index.rb, line 12
def self.ranks klass, ranker
  @rankers[klass] = ranker
end
set_default_position(instance) click to toggle source
# File lib/rankle_index.rb, line 16
def self.set_default_position instance
  if @rankers[instance.class] && @rankers[instance.class].strategy
    position = instance.class.ranked.each_with_index { |record, index| break index if @rankers[instance.class].strategy.call(instance, record) } unless @rankers[instance.class].strategy.is_a?(Symbol)
  end
  position = position.count if position.is_a?(ActiveRecord::Relation)
  position = instance.class.count - 1 if position.nil? || position.is_a?(Array)
  instance.rank position
  if @rankers[instance.class] && @rankers[instance.class].strategy.is_a?(Symbol)
    instance.rank @rankers[instance.class].strategy, RankleIndex.where(indexable_name: @rankers[instance.class].strategy).count
  end
end