Orbit/app/models/mongoid/sortable.rb

35 lines
685 B
Ruby
Raw Permalink Normal View History

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
if self.new? && self.sort_number.nil?
last_record = self.class.desc(:sort_number).first
2013-06-13 06:33:15 +00:00
if last_record && last_record.sort_number
self.sort_number = (last_record.sort_number + 10) / 10 * 10
else
self.sort_number = 10
end
end
end
end
end