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-2.0.2 lib/kuhsaft/orderable.rb
kuhsaft-1.8.4 lib/kuhsaft/orderable.rb
kuhsaft-1.8.1 lib/kuhsaft/orderable.rb
kuhsaft-2.0.1 lib/kuhsaft/orderable.rb
kuhsaft-2.0.0 lib/kuhsaft/orderable.rb
kuhsaft-1.8.0 lib/kuhsaft/orderable.rb
kuhsaft-1.7.1 lib/kuhsaft/orderable.rb
kuhsaft-1.7.0 lib/kuhsaft/orderable.rb
kuhsaft-1.6.0 lib/kuhsaft/orderable.rb
kuhsaft-1.5.0 lib/kuhsaft/orderable.rb
kuhsaft-1.4.3 lib/kuhsaft/orderable.rb
kuhsaft-1.4.2 lib/kuhsaft/orderable.rb
kuhsaft-1.4.1 lib/kuhsaft/orderable.rb
kuhsaft-1.4.0 lib/kuhsaft/orderable.rb
kuhsaft-1.3.1 lib/kuhsaft/orderable.rb
kuhsaft-0.3.6 lib/kuhsaft/orderable.rb
kuhsaft-0.3.5 lib/kuhsaft/orderable.rb
kuhsaft-1.2.15 lib/kuhsaft/orderable.rb
kuhsaft-1.2.14 lib/kuhsaft/orderable.rb
kuhsaft-1.2.13 lib/kuhsaft/orderable.rb