Module: Lexorank::Rankable::InstanceMethods

Defined in:
lib/lexorank/rankable.rb

Instance Method Summary collapse

Instance Method Details

#move_to(position) ⇒ Object



48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
# 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
      # if item is currently in front of the index we just use position otherwise position - 1
      # if the item has no rank we use position - 1
      position -= 1 if !self.send(self.class.ranking_column) || collection.map(&:id).index(self.id) > position
      collection.offset(position).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) ⇒ Object



79
80
81
82
# File 'lib/lexorank/rankable.rb', line 79

def move_to!(position)
  move_to(position)
  save
end

#move_to_topObject



44
45
46
# File 'lib/lexorank/rankable.rb', line 44

def move_to_top
  move_to(0)
end

#move_to_top!Object



84
85
86
# File 'lib/lexorank/rankable.rb', line 84

def move_to_top!
  move_to!(0)
end