Sha256: 01089a69c0beaaf501d24c217b4887c8cff170f499750584b372596debd673fb

Contents?: true

Size: 1.04 KB

Versions: 62

Compression:

Stored size: 1.04 KB

Contents

module Workarea
  # TODO extract to gem
  module Ordering
    extend ActiveSupport::Concern

    included do
      field :position, type: Integer

      after_validation :set_position
      after_create :move_lower_blocks_down
      after_destroy :move_lower_blocks_up

      default_scope -> { asc(:position) }
    end

    def lower_siblings
      siblings.where(:position.gte => position).excludes(id: id)
    end

    def higher_siblings
      siblings.where(:position.lte => position).excludes(id: id)
    end

    private

    def siblings
      return self.class.all unless embedded?
      return self.class.none unless _parent.present?

      _parent.send(relation_metadata.name).criteria
    end

    def set_position
      if position.blank?
        self.position = siblings.exists(position: true).length
      end
    end

    def move_lower_blocks_down
      lower_siblings.select(&:persisted?).each { |b| b.inc(position: 1) }
    end

    def move_lower_blocks_up
      lower_siblings.select(&:persisted?).each { |b| b.inc(position: -1) }
    end
  end
end

Version data entries

62 entries across 62 versions & 1 rubygems

Version Path
workarea-core-3.5.27 app/models/workarea/ordering.rb
workarea-core-3.5.26 app/models/workarea/ordering.rb
workarea-core-3.4.45 app/models/workarea/ordering.rb
workarea-core-3.5.25 app/models/workarea/ordering.rb
workarea-core-3.5.23 app/models/workarea/ordering.rb
workarea-core-3.4.44 app/models/workarea/ordering.rb
workarea-core-3.5.22 app/models/workarea/ordering.rb
workarea-core-3.4.43 app/models/workarea/ordering.rb
workarea-core-3.5.21 app/models/workarea/ordering.rb
workarea-core-3.4.42 app/models/workarea/ordering.rb
workarea-core-3.5.20 app/models/workarea/ordering.rb
workarea-core-3.4.41 app/models/workarea/ordering.rb
workarea-core-3.5.19 app/models/workarea/ordering.rb
workarea-core-3.4.40 app/models/workarea/ordering.rb
workarea-core-3.5.18 app/models/workarea/ordering.rb
workarea-core-3.4.39 app/models/workarea/ordering.rb
workarea-core-3.5.17 app/models/workarea/ordering.rb
workarea-core-3.4.38 app/models/workarea/ordering.rb
workarea-core-3.5.16 app/models/workarea/ordering.rb
workarea-core-3.4.37 app/models/workarea/ordering.rb