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
- #next ⇒ Object
- #position_at(new_position) ⇒ Object
- #position_scope(_options = {}) ⇒ Object
- #previous ⇒ Object
- #relation ⇒ Object
- #reorder(ids) ⇒ Object
- #set_position ⇒ Object
- #set_sibling_positions ⇒ Object
Instance Method Details
#next ⇒ Object
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( = {}) scopes = Array([:scope]) scopes.inject(relation) do |criteria, scope_field| criteria.where(scope_field => send(scope_field)) end end |
#previous ⇒ Object
32 33 34 |
# File 'lib/mongoid-sortable.rb', line 32 def previous position_scope.lt(position: position).order_by('position desc').first end |
#relation ⇒ Object
62 63 64 |
# File 'lib/mongoid-sortable.rb', line 62 def relation ( ? 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_position ⇒ Object
54 55 56 |
# File 'lib/mongoid-sortable.rb', line 54 def set_position self.position = position_scope.count + ( ? 0 : 1) end |
#set_sibling_positions ⇒ Object
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 |