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.15 app/models/workarea/ordering.rb
workarea-core-3.4.36 app/models/workarea/ordering.rb
workarea-core-3.5.14 app/models/workarea/ordering.rb
workarea-core-3.4.35 app/models/workarea/ordering.rb
workarea-core-3.5.13 app/models/workarea/ordering.rb
workarea-core-3.4.34 app/models/workarea/ordering.rb
workarea-core-3.5.12 app/models/workarea/ordering.rb
workarea-core-3.4.33 app/models/workarea/ordering.rb
workarea-core-3.5.11 app/models/workarea/ordering.rb
workarea-core-3.5.10 app/models/workarea/ordering.rb
workarea-core-3.4.32 app/models/workarea/ordering.rb
workarea-core-3.5.9 app/models/workarea/ordering.rb
workarea-core-3.4.31 app/models/workarea/ordering.rb
workarea-core-3.5.8 app/models/workarea/ordering.rb
workarea-core-3.4.30 app/models/workarea/ordering.rb
workarea-core-3.5.7 app/models/workarea/ordering.rb
workarea-core-3.4.29 app/models/workarea/ordering.rb
workarea-core-3.5.6 app/models/workarea/ordering.rb
workarea-core-3.4.28 app/models/workarea/ordering.rb
workarea-core-3.5.5 app/models/workarea/ordering.rb