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
- #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
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( = {}) scopes = Array([:scope]) scopes.inject(relation) do |criteria, scope_field| criteria.where(scope_field => self.send(scope_field)) end end |
#previous ⇒ Object
30 31 32 |
# File 'lib/mongoid-sortable.rb', line 30 def previous position_scope.lt(position: position).order_by('position desc').first end |
#relation ⇒ Object
60 61 62 |
# File 'lib/mongoid-sortable.rb', line 60 def relation ( ? 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_position ⇒ Object
52 53 54 |
# File 'lib/mongoid-sortable.rb', line 52 def set_position self.position = position_scope.count + ( ? 0 : 1) end |
#set_sibling_positions ⇒ Object
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 |