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 =
'1.0.1'

Instance Method Summary collapse

Instance Method Details

#nextObject



36
37
38
# File 'lib/mongoid-sortable.rb', line 36

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

#position_at(new_position) ⇒ Object



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

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



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

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

#previousObject



32
33
34
# File 'lib/mongoid-sortable.rb', line 32

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

#relationObject



62
63
64
# File 'lib/mongoid-sortable.rb', line 62

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

#reorder(ids) ⇒ Object



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

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



54
55
56
# File 'lib/mongoid-sortable.rb', line 54

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

#set_sibling_positionsObject



58
59
60
# File 'lib/mongoid-sortable.rb', line 58

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