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.4.27 app/models/workarea/ordering.rb
workarea-core-3.5.4 app/models/workarea/ordering.rb
workarea-core-3.4.26 app/models/workarea/ordering.rb
workarea-core-3.5.3 app/models/workarea/ordering.rb
workarea-core-3.4.25 app/models/workarea/ordering.rb
workarea-core-3.5.2 app/models/workarea/ordering.rb
workarea-core-3.4.24 app/models/workarea/ordering.rb
workarea-core-3.5.1 app/models/workarea/ordering.rb
workarea-core-3.4.23 app/models/workarea/ordering.rb
workarea-core-3.4.22 app/models/workarea/ordering.rb
workarea-core-3.5.0 app/models/workarea/ordering.rb
workarea-core-3.4.21 app/models/workarea/ordering.rb
workarea-core-3.5.0.beta.1 app/models/workarea/ordering.rb
workarea-core-3.4.20 app/models/workarea/ordering.rb
workarea-core-3.4.19 app/models/workarea/ordering.rb
workarea-core-3.4.18 app/models/workarea/ordering.rb
workarea-core-3.4.17 app/models/workarea/ordering.rb
workarea-core-3.4.16 app/models/workarea/ordering.rb
workarea-core-3.4.15 app/models/workarea/ordering.rb
workarea-core-3.4.14 app/models/workarea/ordering.rb