Sha256: b55bea124b98a06ce1929a00805d3ac83b0bc3d9db485fcb25820322e7909743

Contents?: true

Size: 1.69 KB

Versions: 1

Compression:

Stored size: 1.69 KB

Contents

require 'nested_set'
include CollectiveIdea::Acts::NestedSet

module SortableNestedSet
  def self.included(base)
    base.extend ClassMethods
    base.send :include, InstanceMethods
  end

  module ClassMethods
    def acts_as_sortable_nested_set_of(items_type)
      @subcategories_type = "sub#{name.tableize}".to_sym
      @items_type = items_type

      instance_eval do
        def sns_subcategories_type ; @subcategories_type end
        def sns_items_type ; @items_type end
      end

      class_eval do
        define_method(:sns_subcategories) { send(self.class.sns_subcategories_type) }
        define_method(:sns_items) { send(self.class.sns_items_type) }
      end

      acts_as_nested_set :parent_column => name.foreign_key

      attr_accessible parent_column_name

      belongs_to name.underscore.to_sym

      has_many @subcategories_type, :class_name => name, :dependent => :destroy
      has_many @items_type, :order => :position, :dependent => :destroy

      scope :for_indented_list,
            :select => [parent_column_name, :id, :name, left_column_name, right_column_name],
            :order => left_column_name
      scope :for_indented_list_with_items, lambda { self.for_indented_list.includes(sns_items_type) }
    end
  end

  module InstanceMethods
    def move(parent, children)
      if children.size == 1
        move_to_child_of(parent)
      else
        prev_sibling = nil

        for i in 0...children.size
          if children[i] == id
            prev_sibling ? move_to_right_of(prev_sibling) : move_to_left_of(children[i+1])
            break
          end

          prev_sibling = children[i]
        end
      end
    end
  end
end

ActiveRecord::Base.send :include, SortableNestedSet

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
sortable_nested_set-0.2.2 lib/sortable_nested_set/acts_as_sortable_nested_set.rb