Module: Mongoid::Sortable

Extended by:
ActiveSupport::Concern
Defined in:
lib/mongoid-sortable.rb,
lib/mongoid-sortable/version.rb

Defined Under Namespace

Modules: ClassMethods

Constant Summary collapse

VERSION =
"0.0.1"

Instance Method Summary collapse

Instance Method Details

#nextObject



34
35
36
# File 'lib/mongoid-sortable.rb', line 34

def next
  position_scope.gt(position: position).order_by('position asc').first
end

#position_at(new_position) ⇒ Object



45
46
47
48
49
50
# File 'lib/mongoid-sortable.rb', line 45

def position_at(new_position)
  position_scope.gt(position: position).each{|d| d.inc(:position, -1) }
  set(:position, nil)
  position_scope.gte(position: new_position).each{|d| d.inc(:position, 1) }
  set(:position, new_position)
end

#position_scope(options = {}) ⇒ Object



64
65
66
67
68
69
# File 'lib/mongoid-sortable.rb', line 64

def position_scope(options = {})
  scopes = Array(mongoid_sortable_options[:scope])
  scopes.inject(relation) do |criteria, scope_field|
    criteria.where(scope_field => self.send(scope_field))
  end
end

#previousObject



30
31
32
# File 'lib/mongoid-sortable.rb', line 30

def previous
  position_scope.lt(position: position).order_by('position desc').first
end

#relationObject



60
61
62
# File 'lib/mongoid-sortable.rb', line 60

def relation
  (embedded? ? send(self..inverse).send(self..name) : self.class).unscoped.scoped
end

#reorder(ids) ⇒ Object



38
39
40
41
42
43
# File 'lib/mongoid-sortable.rb', line 38

def reorder(ids)
  ids.map!(&:to_s) # ensure entities are strings
  ids.each_with_index do |id, index|
    position_scope.find(id).set(:position, index + 1)
  end
end

#set_positionObject



52
53
54
# File 'lib/mongoid-sortable.rb', line 52

def set_position
  self.position = position_scope.count + (embedded? ? 0 : 1)
end

#set_sibling_positionsObject



56
57
58
# File 'lib/mongoid-sortable.rb', line 56

def set_sibling_positions
  position_scope.gt(position: position).each{|d| d.inc(:position, -1) }
end