Sha256: 83e64b4279b2ee9a8fb49b716f9e6b811b4914e5ae6b26dff7e228cd7ab13d1b

Contents?: true

Size: 1.76 KB

Versions: 72

Compression:

Stored size: 1.76 KB

Contents

module Kuhsaft
  # If you use this mixin, your class must implement the following methods
  # siblings(), returns the siblings of the same type of object
  
  module Orderable
    def self.included base
      base.extend(ClassMethods)
      base.send :include, InstanceMethods
      base.after_create :set_position
    end
    
    module InstanceMethods
      def increment_position
        update_attribute :position, position + 1
      end
  
      def decrement_position
        update_attribute :position, position - 1
      end
  
      def preceding_sibling
        siblings.where('position = ?', position - 1).first
      end
  
      def succeeding_sibling
        siblings.where('position = ?', position + 1).first
      end
  
      def preceding_siblings
        siblings.where('position <= ?', position).where('id != ?', id)
      end
  
      def succeeding_siblings
        siblings.where('position >= ?', position).where('id != ?', id)
      end
  
      def position_to_top
        update_attribute :position, 1
        recount_siblings_position_from 1
      end
  
      def recount_siblings_position_from position
        counter = position
        succeeding_siblings.each { |s| counter += 1; s.update_attribute(:position, counter) }
      end
  
      def reposition before_id
        if before_id.blank?
          position_to_top
        else
          update_attribute :position, self.class.position_of(before_id) + 1
          recount_siblings_position_from position
        end
      end
  
      def set_position
        initial_position = siblings.blank? ? 1 : siblings.count + 1
        update_attribute(:position, initial_position)
      end
    end
    
    module ClassMethods
      def position_of id
        self.find(id).position rescue 1
      end
    end
  end
end

Version data entries

72 entries across 72 versions & 1 rubygems

Version Path
kuhsaft-0.2.legacy4 lib/kuhsaft/orderable.rb
kuhsaft-0.3.4.legacy3 lib/kuhsaft/orderable.rb
kuhsaft-2.2.6 lib/kuhsaft/orderable.rb
kuhsaft-2.2.5 lib/kuhsaft/orderable.rb
kuhsaft-2.2.4 lib/kuhsaft/orderable.rb
kuhsaft-2.2.3 lib/kuhsaft/orderable.rb
kuhsaft-2.2.2 lib/kuhsaft/orderable.rb
kuhsaft-2.2.1 lib/kuhsaft/orderable.rb
kuhsaft-2.2.0 lib/kuhsaft/orderable.rb
kuhsaft-2.1.2 lib/kuhsaft/orderable.rb
kuhsaft-2.1.1 lib/kuhsaft/orderable.rb
kuhsaft-0.2.legacy3 lib/kuhsaft/orderable.rb
kuhsaft-0.2.legacy2 lib/kuhsaft/orderable.rb
kuhsaft-0.2.legacy lib/kuhsaft/orderable.rb
kuhsaft-0.3.4.legacy2 lib/kuhsaft/orderable.rb
kuhsaft-0.3.4.legacy lib/kuhsaft/orderable.rb
kuhsaft-2.1.0 lib/kuhsaft/orderable.rb
kuhsaft-1.8.6 lib/kuhsaft/orderable.rb
kuhsaft-1.8.5 lib/kuhsaft/orderable.rb
kuhsaft-2.0.3 lib/kuhsaft/orderable.rb