module Lexorank::Rankable::InstanceMethods

Public Instance Methods

move_to(position) click to toggle source
# File lib/lexorank/rankable.rb, line 48
def move_to(position)
  collection = self.class.ranked
  if self.class.ranking_group_by.present?
    collection = collection.where("#{self.class.ranking_group_by}": send(self.class.ranking_group_by))
  end

  # exceptions:
  #   move to the beginning (aka move to position 0)
  #   move to end (aka position = collection.size - 1)
  # when moving to the end of the collection the offset and limit statement automatically handles
  # that 'after' is nil which is the same like [collection.last, nil]
  before, after =
    if position == 0
      [nil, collection.first]
    else
      collection.where.not(id: self.id).offset(position - 1).limit(2)
    end

  rank =
    if self == after && self.send(self.class.ranking_column).present?
      self.send(self.class.ranking_column)
    else
      value_between(before&.send(self.class.ranking_column), after&.send(self.class.ranking_column))
    end

  self.send("#{self.class.ranking_column}=", rank)
end
move_to!(position) click to toggle source
# File lib/lexorank/rankable.rb, line 76
def move_to!(position)
  move_to(position)
  save
end
move_to_top() click to toggle source
# File lib/lexorank/rankable.rb, line 44
def move_to_top
  move_to(0)
end
move_to_top!() click to toggle source
# File lib/lexorank/rankable.rb, line 81
def move_to_top!
  move_to!(0)
end
no_rank?() click to toggle source
# File lib/lexorank/rankable.rb, line 85
def no_rank?
  !self.send(self.class.ranking_column)
end