Sha256: 6f874ca82df63c14da4b89cc387be42f83bff6ab27fd25e152214ac27e68a34e

Contents?: true

Size: 1.17 KB

Versions: 9

Compression:

Stored size: 1.17 KB

Contents

module Callbacks
  class UniqueKeyBeforeUpdate
    include Restrictor

    def init
      # keep position and position_was, because buffered_position rewrites them
      @position, @position_was = m.position, m.position_was
      if @position_was < @position
        # move list range downward
        @range = (@position_was + 1)..@position
        @reverse = false
      else
        # move list range upward
        @range = @position..(@position_was - 1)
        @reverse = true
      end
    end

    def call
      m.with_buffered_position(@position) do
        update_list
        m.other_locales(@position_was).each do |unique_key|
          unique_key.with_buffered_position(@position) do
            update_list(unique_key.locale)
          end
        end
      end
    end

    private

    def update_list(locale = nil)
      query = m.list(locale).where(position: @range).order(:position)
      if @reverse
        query = query.reverse_order
      end

      query.each.with_index do |unique_key, i|
        position = @reverse ? m.position_was - i : m.position_was + i

        unique_key.update_column(:position, position)
        unique_key.viewable.touch
      end
    end
  end
end

Version data entries

9 entries across 9 versions & 1 rubygems

Version Path
rails_admin_cms-0.1.1 app/models/callbacks/unique_key_before_update.rb
rails_admin_cms-0.0.9 app/models/callbacks/unique_key_before_update.rb
rails_admin_cms-0.0.7 app/models/callbacks/unique_key_before_update.rb
rails_admin_cms-0.0.6 app/models/callbacks/unique_key_before_update.rb
rails_admin_cms-0.0.5 app/models/callbacks/unique_key_before_update.rb
rails_admin_cms-0.0.4 app/models/callbacks/unique_key_before_update.rb
rails_admin_cms-0.0.3 app/models/callbacks/unique_key_before_update.rb
rails_admin_cms-0.0.2 app/models/callbacks/unique_key_before_update.rb
rails_admin_cms-0.0.1 app/models/callbacks/unique_key_before_update.rb