Sha256: 0ff34b5faa755a170df08145c703b44639e668fec7bd32ce56cb24b7791da380

Contents?: true

Size: 1.54 KB

Versions: 6

Compression:

Stored size: 1.54 KB

Contents

module Adminpanel
  module Sortable
    extend ActiveSupport::Concern
    # the lower the (position) integer is, the better it is.

    included do
      before_create :set_position
      before_destroy :rearrange_positions

      default_scope do
        order('position ASC')
      end
    end

    module ClassMethods
      def is_sortable?
        true
      end
    end

    def move_to_better_position
      if self.position > 1
        conflicting_gallery(self.position - 1).increment!(:position)
        self.decrement!(:position)

        true
      else
        false
      end
    end

    def move_to_worst_position
      records = self.class.count
      if self.position < records
        conflicting_gallery(self.position + 1).decrement!(:position)
        self.increment!(:position)
        true
      else
        false
      end
    end

    protected
      def conflicting_gallery(conflicting_position)
        logger.info "searching pos: #{conflicting_position}"
        self.class.find_by_position(conflicting_position)
      end

      def rearrange_positions
        unarranged_records = self.class.where(
          'position > ?', self.position
        )
        unarranged_records.each do |record|
          record.update_attribute(:position, gallery.position - 1)
        end

      end

      def set_position
        last_record = self.class.last
        if last_record.nil?
          # this is the first record that is created
          self.position = 1
        else
          self.position = last_record.position + 1
        end
      end
  end
end

Version data entries

6 entries across 6 versions & 1 rubygems

Version Path
adminpanel-2.4.3 app/models/concerns/adminpanel/sortable.rb
adminpanel-2.4.2 app/models/concerns/adminpanel/sortable.rb
adminpanel-2.4.1 app/models/concerns/adminpanel/sortable.rb
adminpanel-2.4.0 app/models/concerns/adminpanel/sortable.rb
adminpanel-2.3.1 app/models/concerns/adminpanel/sortable.rb
adminpanel-2.3.0 app/models/concerns/adminpanel/sortable.rb