Sha256: 658769473c7514d77d0eebcc43ca2b3d13e4a6e91a07e491c9da6e6fac6c670c

Contents?: true

Size: 1.85 KB

Versions: 5

Compression:

Stored size: 1.85 KB

Contents

module Adminpanel
  module Galleryzation
    extend ActiveSupport::Concern

    included do
      before_create :set_position
      before_destroy :rearrange_positions

      scope :ordered, -> do
        order('position ASC')
        # where(position: 1)
      end

    end

    def move_to_better_position
      if self.position > 1
        conflicting_gallery = get_conflicting_gallery(position - 1)

        self.update_attribute(:position, self.position - 1)

        conflicting_gallery.update_attribute(
          :position, conflicting_gallery.position + 1
        )
        true
      else
        false
      end
    end

    def move_to_worst_position
      records = self.class.count
      if self.position < records
        conflicting_gallery = get_conflicting_gallery(position + 1)

        update_attribute(:position, self.position + 1)

        conflicting_gallery.update_attribute(
          :position, conflicting_gallery.position - 1
        )
        true
      else
        false
      end
    end

  protected
    def get_conflicting_gallery(conflicting_position)
      self.class.where(
        self.class.relation_field => self.send(self.class.relation_field)
      ).find_by_position(conflicting_position)
    end

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

    end

    def set_position
      last_record = self.class.where(
        self.class.relation_field => self.send(
          self.class.relation_field
        )
      ).last
      if last_record.nil?
        self.position = 1
      else
        self.position = last_record.position + 1
      end
    end
  end
end

Version data entries

5 entries across 5 versions & 1 rubygems

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