2013-06-04 02:53:31 +00:00
|
|
|
module Mongoid
|
|
|
|
module Sortable
|
|
|
|
extend ActiveSupport::Concern
|
|
|
|
|
|
|
|
included do
|
|
|
|
field :sort_number, type: Integer
|
|
|
|
|
|
|
|
after_initialize :set_sort_number
|
|
|
|
end
|
|
|
|
|
|
|
|
module ClassMethods
|
|
|
|
def default_sort(sorted = true)
|
|
|
|
if !sorted
|
|
|
|
asc(:sort_number)
|
|
|
|
else
|
|
|
|
asc
|
|
|
|
end
|
|
|
|
end
|
|
|
|
end
|
|
|
|
|
|
|
|
private
|
|
|
|
|
|
|
|
def set_sort_number
|
2013-06-06 14:19:44 +00:00
|
|
|
if self.new? && self.sort_number.nil?
|
2013-06-04 02:53:31 +00:00
|
|
|
last_record = self.class.desc(:sort_number).first
|
2013-06-13 06:33:15 +00:00
|
|
|
if last_record && last_record.sort_number
|
2013-06-04 02:53:31 +00:00
|
|
|
self.sort_number = (last_record.sort_number + 10) / 10 * 10
|
|
|
|
else
|
|
|
|
self.sort_number = 10
|
|
|
|
end
|
|
|
|
end
|
|
|
|
end
|
|
|
|
end
|
|
|
|
end
|