Gemfile: use awesome_nested_set 2.1.6 gem

git-svn-id: http://svn.redmine.org/redmine/trunk@12734 e93f8b46-1217-0410-a6f0-8f06a7374b81
This commit is contained in:
Toshi MARUYAMA 2014-01-27 06:48:38 +00:00
parent ba75aa504b
commit 9e71d89cdb
24 changed files with 1 additions and 2708 deletions

View File

@ -6,6 +6,7 @@ gem "coderay", "~> 1.1.0"
gem "fastercsv", "~> 1.5.0", :platforms => [:mri_18, :mingw_18, :jruby]
gem "builder", "3.0.0"
gem "mime-types"
gem "awesome_nested_set", "2.1.6"
# Optional gem for LDAP authentication
group :ldap do

View File

@ -1,13 +0,0 @@
Autotest.add_hook :initialize do |at|
at.clear_mappings
at.add_mapping %r%^lib/(.*)\.rb$% do |_, m|
at.files_matching %r%^test/#{m[1]}_test.rb$%
end
at.add_mapping(%r%^test/.*\.rb$%) {|filename, _| filename }
at.add_mapping %r%^test/fixtures/(.*)s.yml% do |_, _|
at.files_matching %r%^test/.*\.rb$%
end
end

View File

@ -1,22 +0,0 @@
language: ruby
notifications:
email:
- parndt@gmail.com
script: bundle exec rspec spec
env:
- DB=sqlite3
- DB=sqlite3mem
- DB=postgresql
- DB=mysql
rvm:
- 2.0.0
- 1.9.3
- 1.8.7
- rbx-19mode
- jruby-19mode
- rbx-18mode
- jruby-18mode
gemfile:
- gemfiles/Gemfile.rails-3.0.rb
- gemfiles/Gemfile.rails-3.1.rb
- gemfiles/Gemfile.rails-3.2.rb

View File

@ -1,57 +0,0 @@
2.1.6
* Fixed rebuild! when there is a default_scope with order [Adrian Serafin]
* Testing with stable bundler, ruby 2.0, MySQL and PostgreSQL [Philip Arndt]
* Optimized move_to for large trees [ericsmith66]
2.1.5
* Worked around issues where AR#association wasn't present on Rails 3.0.x. [Philip Arndt]
* Adds option 'order_column' which defaults to 'left_column_name'. [gudata]
* Added moving with order functionality. [Sytse Sijbrandij]
* Use tablename in all select queries. [Mikhail Dieterle]
* Made sure all descendants' depths are updated when moving parent, not just immediate child. [Phil Thompson]
* Add documentation of the callbacks. [Tobias Maier]
2.1.4
* nested_set_options accept both Class & AR Relation. [Semyon Perepelitsa]
* Reduce the number of queries triggered by the canonical usage of `i.level` in the `nested_set` helpers. [thedarkone]
* Specifically require active_record [Bogdan Gusiev]
* compute_level now checks for a non nil association target. [Joel Nimety]
2.1.3
* Update child depth when parent node is moved. [Amanda Wagener]
* Added move_to_child_with_index. [Ben Zhang]
* Optimised self_and_descendants for when there's an index on lft. [Mark Torrance]
* Added support for an unsaved record to return the right 'root'. [Philip Arndt]
2.1.2
* Fixed regressions introduced. [Philip Arndt]
2.1.1
* Added 'depth' which indicates how many levels deep the node is.
This only works when you have a column called 'depth' in your table,
otherwise it doesn't set itself. [Philip Arndt]
* Rails 3.2 support added. [Gabriel Sobrinho]
* Oracle compatibility added. [Pikender Sharma]
* Adding row locking to deletion, locking source of pivot values, and adding retry on collisions. [Markus J. Q. Roberts]
* Added method and helper for sorting children by column. [bluegod]
* Fixed .all_roots_valid? to work with Postgres. [Joshua Clayton]
* Made compatible with polymorphic belongs_to. [Graham Randall]
* Added in the association callbacks to the children :has_many association. [Michael Deering]
* Modified helper to allow using array of objects as argument. [Rahmat Budiharso]
* Fixed cases where we were calling attr_protected. [Jacob Swanner]
* Fixed nil cases involving lft and rgt. [Stuart Coyle] and [Patrick Morgan]
2.0.2
* Fixed deprecation warning under Rails 3.1 [Philip Arndt]
* Converted Test::Unit matchers to RSpec. [Uģis Ozols]
* Added inverse_of to associations to improve performance rendering trees. [Sergio Cambra]
* Added row locking and fixed some race conditions. [Markus J. Q. Roberts]
2.0.1
* Fixed a bug with move_to not using nested_set_scope [Andreas Sekine]
2.0.0.pre
* Expect Rails 3
* Changed how callbacks work. Returning false in a before_move action does not block save operations. Use a validation or exception in the callback if you need that.
* Switched to RSpec
* Remove use of Comparable

View File

@ -1,20 +0,0 @@
Copyright (c) 2007-2011 Collective Idea
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

View File

@ -1,153 +0,0 @@
= AwesomeNestedSet
Awesome Nested Set is an implementation of the nested set pattern for ActiveRecord models. It is replacement for acts_as_nested_set and BetterNestedSet, but more awesome.
Version 2 supports Rails 3. Gem versions prior to 2.0 support Rails 2.
== What makes this so awesome?
This is a new implementation of nested set based off of BetterNestedSet that fixes some bugs, removes tons of duplication, adds a few useful methods, and adds STI support.
== Installation
Add to your Gemfile:
gem 'awesome_nested_set'
== Usage
To make use of awesome_nested_set, your model needs to have 3 fields: lft, rgt, and parent_id.
You can also have an optional field: depth:
class CreateCategories < ActiveRecord::Migration
def self.up
create_table :categories do |t|
t.string :name
t.integer :parent_id
t.integer :lft
t.integer :rgt
t.integer :depth # this is optional.
end
end
def self.down
drop_table :categories
end
end
Enable the nested set functionality by declaring acts_as_nested_set on your model
class Category < ActiveRecord::Base
acts_as_nested_set
end
Run `rake rdoc` to generate the API docs and see CollectiveIdea::Acts::NestedSet for more info.
== Callbacks
There are three callbacks called when moving a node. `before_move`, `after_move` and `around_move`.
class Category < ActiveRecord::Base
acts_as_nested_set
after_move :rebuild_slug
around_move :da_fancy_things_around
private
def rebuild_slug
# do whatever
end
def da_fancy_things_around
# do something...
yield # actually moves
# do something else...
end
end
Beside this there are also hooks to act on the newly added or removed children.
class Category < ActiveRecord::Base
acts_as_nested_set :before_add => :do_before_add_stuff,
:after_add => :do_after_add_stuff,
:before_remove => :do_before_remove_stuff,
:after_remove => :do_after_remove_stuff
private
def do_before_add_stuff(child_node)
# do whatever with the child
end
def do_after_add_stuff(child_node)
# do whatever with the child
end
def do_before_remove_stuff(child_node)
# do whatever with the child
end
def do_after_remove_stuff(child_node)
# do whatever with the child
end
end
== Protecting attributes from mass assignment
It's generally best to "white list" the attributes that can be used in mass assignment:
class Category < ActiveRecord::Base
acts_as_nested_set
attr_accessible :name, :parent_id
end
If for some reason that is not possible, you will probably want to protect the lft and rgt attributes:
class Category < ActiveRecord::Base
acts_as_nested_set
attr_protected :lft, :rgt
end
== Conversion from other trees
Coming from acts_as_tree or another system where you only have a parent_id? No problem. Simply add the lft & rgt fields as above, and then run
Category.rebuild!
Your tree will be converted to a valid nested set. Awesome!
== View Helper
The view helper is called #nested_set_options.
Example usage:
<%= f.select :parent_id, nested_set_options(Category, @category) {|i| "#{'-' * i.level} #{i.name}" } %>
<%= select_tag 'parent_id', options_for_select(nested_set_options(Category) {|i| "#{'-' * i.level} #{i.name}" } ) %>
See CollectiveIdea::Acts::NestedSet::Helper for more information about the helpers.
== References
You can learn more about nested sets at: http://threebit.net/tutorials/nestedset/tutorial1.html
== How to contribute
If you find what you might think is a bug:
1. Check the GitHub issue tracker to see if anyone else has had the same issue.
https://github.com/collectiveidea/awesome_nested_set/issues/
2. If you don't see anything, create an issue with information on how to reproduce it.
If you want to contribute an enhancement or a fix:
1. Fork the project on GitHub.
https://github.com/collectiveidea/awesome_nested_set/
2. Make your changes with tests.
3. Commit the changes without making changes to the Rakefile, VERSION, or any other files that aren't related to your enhancement or fix
4. Send a pull request.
Copyright ©2008 Collective Idea, released under the MIT license

View File

@ -1,32 +0,0 @@
# -*- encoding: utf-8 -*-
$LOAD_PATH.unshift File.expand_path("../lib", __FILE__)
require 'rubygems'
require 'bundler/setup'
require 'awesome_nested_set/version'
task :default => :spec
task :spec do
%w(3.0 3.1 3.2).each do |rails_version|
puts "\n" + (cmd = "BUNDLE_GEMFILE='gemfiles/Gemfile.rails-#{rails_version}.rb' bundle exec rspec spec")
system cmd
end
end
task :build do
system "gem build awesome_nested_set.gemspec"
end
task :release => :build do
system "gem push awesome_nested_set-#{ActsAsGeocodable::VERSION}.gem"
end
require 'rdoc/task'
desc 'Generate documentation for the awesome_nested_set plugin.'
Rake::RDocTask.new(:rdoc) do |rdoc|
rdoc.rdoc_dir = 'rdoc'
rdoc.title = 'AwesomeNestedSet'
rdoc.options << '--line-numbers' << '--inline-source'
rdoc.rdoc_files.include('README.rdoc')
rdoc.rdoc_files.include('lib/**/*.rb')
end

View File

@ -1,24 +0,0 @@
# -*- encoding: utf-8 -*-
require File.expand_path('../lib/awesome_nested_set/version', __FILE__)
Gem::Specification.new do |s|
s.name = %q{awesome_nested_set}
s.version = ::AwesomeNestedSet::VERSION
s.authors = ["Brandon Keepers", "Daniel Morrison", "Philip Arndt"]
s.description = %q{An awesome nested set implementation for Active Record}
s.email = %q{info@collectiveidea.com}
s.extra_rdoc_files = %w[README.rdoc]
s.files = Dir.glob("lib/**/*") + %w(MIT-LICENSE README.rdoc CHANGELOG)
s.homepage = %q{http://github.com/collectiveidea/awesome_nested_set}
s.rdoc_options = ["--main", "README.rdoc", "--inline-source", "--line-numbers"]
s.require_paths = ["lib"]
s.rubygems_version = %q{1.3.6}
s.summary = %q{An awesome nested set implementation for Active Record}
s.license = %q{MIT}
s.add_runtime_dependency 'activerecord', '>= 3.0.0'
s.add_development_dependency 'rspec-rails', '~> 2.12'
s.add_development_dependency 'rake', '~> 10'
s.add_development_dependency 'combustion', '>= 0.3.3'
end

View File

@ -1 +0,0 @@
require File.dirname(__FILE__) + '/lib/awesome_nested_set'

View File

@ -1,8 +0,0 @@
require 'awesome_nested_set/awesome_nested_set'
require 'active_record'
ActiveRecord::Base.send :extend, CollectiveIdea::Acts::NestedSet
if defined?(ActionView)
require 'awesome_nested_set/helper'
ActionView::Base.send :include, CollectiveIdea::Acts::NestedSet::Helper
end

View File

@ -1,767 +0,0 @@
module CollectiveIdea #:nodoc:
module Acts #:nodoc:
module NestedSet #:nodoc:
# This acts provides Nested Set functionality. Nested Set is a smart way to implement
# an _ordered_ tree, with the added feature that you can select the children and all of their
# descendants with a single query. The drawback is that insertion or move need some complex
# sql queries. But everything is done here by this module!
#
# Nested sets are appropriate each time you want either an orderd tree (menus,
# commercial categories) or an efficient way of querying big trees (threaded posts).
#
# == API
#
# Methods names are aligned with acts_as_tree as much as possible to make replacment from one
# by another easier.
#
# item.children.create(:name => "child1")
#
# Configuration options are:
#
# * +:parent_column+ - specifies the column name to use for keeping the position integer (default: parent_id)
# * +:left_column+ - column name for left boundry data, default "lft"
# * +:right_column+ - column name for right boundry data, default "rgt"
# * +:depth_column+ - column name for the depth data, default "depth"
# * +:scope+ - restricts what is to be considered a list. Given a symbol, it'll attach "_id"
# (if it hasn't been already) and use that as the foreign key restriction. You
# can also pass an array to scope by multiple attributes.
# Example: <tt>acts_as_nested_set :scope => [:notable_id, :notable_type]</tt>
# * +:dependent+ - behavior for cascading destroy. If set to :destroy, all the
# child objects are destroyed alongside this object by calling their destroy
# method. If set to :delete_all (default), all the child objects are deleted
# without calling their destroy method.
# * +:counter_cache+ adds a counter cache for the number of children.
# defaults to false.
# Example: <tt>acts_as_nested_set :counter_cache => :children_count</tt>
# * +:order_column+ on which column to do sorting, by default it is the left_column_name
# Example: <tt>acts_as_nested_set :order_column => :position</tt>
#
# See CollectiveIdea::Acts::NestedSet::Model::ClassMethods for a list of class methods and
# CollectiveIdea::Acts::NestedSet::Model for a list of instance methods added
# to acts_as_nested_set models
def acts_as_nested_set(options = {})
options = {
:parent_column => 'parent_id',
:left_column => 'lft',
:right_column => 'rgt',
:depth_column => 'depth',
:dependent => :delete_all, # or :destroy
:polymorphic => false,
:counter_cache => false
}.merge(options)
if options[:scope].is_a?(Symbol) && options[:scope].to_s !~ /_id$/
options[:scope] = "#{options[:scope]}_id".intern
end
class_attribute :acts_as_nested_set_options
self.acts_as_nested_set_options = options
include CollectiveIdea::Acts::NestedSet::Model
include Columns
extend Columns
belongs_to :parent, :class_name => self.base_class.to_s,
:foreign_key => parent_column_name,
:counter_cache => options[:counter_cache],
:inverse_of => (:children unless options[:polymorphic]),
:polymorphic => options[:polymorphic]
has_many_children_options = {
:class_name => self.base_class.to_s,
:foreign_key => parent_column_name,
:order => order_column,
:inverse_of => (:parent unless options[:polymorphic]),
}
# Add callbacks, if they were supplied.. otherwise, we don't want them.
[:before_add, :after_add, :before_remove, :after_remove].each do |ar_callback|
has_many_children_options.update(ar_callback => options[ar_callback]) if options[ar_callback]
end
has_many :children, has_many_children_options
attr_accessor :skip_before_destroy
before_create :set_default_left_and_right
before_save :store_new_parent
after_save :move_to_new_parent, :set_depth!
before_destroy :destroy_descendants
# no assignment to structure fields
[left_column_name, right_column_name, depth_column_name].each do |column|
module_eval <<-"end_eval", __FILE__, __LINE__
def #{column}=(x)
raise ActiveRecord::ActiveRecordError, "Unauthorized assignment to #{column}: it's an internal field handled by acts_as_nested_set code, use move_to_* methods instead."
end
end_eval
end
define_model_callbacks :move
end
module Model
extend ActiveSupport::Concern
included do
delegate :quoted_table_name, :to => self
end
module ClassMethods
# Returns the first root
def root
roots.first
end
def roots
where(parent_column_name => nil).order(quoted_left_column_full_name)
end
def leaves
where("#{quoted_right_column_full_name} - #{quoted_left_column_full_name} = 1").order(quoted_left_column_full_name)
end
def valid?
left_and_rights_valid? && no_duplicates_for_columns? && all_roots_valid?
end
def left_and_rights_valid?
## AS clause not supported in Oracle in FROM clause for aliasing table name
joins("LEFT OUTER JOIN #{quoted_table_name}" +
(connection.adapter_name.match(/Oracle/).nil? ? " AS " : " ") +
"parent ON " +
"#{quoted_parent_column_full_name} = parent.#{primary_key}").
where(
"#{quoted_left_column_full_name} IS NULL OR " +
"#{quoted_right_column_full_name} IS NULL OR " +
"#{quoted_left_column_full_name} >= " +
"#{quoted_right_column_full_name} OR " +
"(#{quoted_parent_column_full_name} IS NOT NULL AND " +
"(#{quoted_left_column_full_name} <= parent.#{quoted_left_column_name} OR " +
"#{quoted_right_column_full_name} >= parent.#{quoted_right_column_name}))"
).count == 0
end
def no_duplicates_for_columns?
scope_string = Array(acts_as_nested_set_options[:scope]).map do |c|
connection.quote_column_name(c)
end.push(nil).join(", ")
[quoted_left_column_full_name, quoted_right_column_full_name].all? do |column|
# No duplicates
select("#{scope_string}#{column}, COUNT(#{column})").
group("#{scope_string}#{column}").
having("COUNT(#{column}) > 1").
first.nil?
end
end
# Wrapper for each_root_valid? that can deal with scope.
def all_roots_valid?
if acts_as_nested_set_options[:scope]
roots.group_by {|record| scope_column_names.collect {|col| record.send(col.to_sym) } }.all? do |scope, grouped_roots|
each_root_valid?(grouped_roots)
end
else
each_root_valid?(roots)
end
end
def each_root_valid?(roots_to_validate)
left = right = 0
roots_to_validate.all? do |root|
(root.left > left && root.right > right).tap do
left = root.left
right = root.right
end
end
end
# Rebuilds the left & rights if unset or invalid.
# Also very useful for converting from acts_as_tree.
def rebuild!(validate_nodes = true)
# default_scope with order may break database queries so we do all operation without scope
unscoped do
# Don't rebuild a valid tree.
return true if valid?
scope = lambda{|node|}
if acts_as_nested_set_options[:scope]
scope = lambda{|node|
scope_column_names.inject(""){|str, column_name|
str << "AND #{connection.quote_column_name(column_name)} = #{connection.quote(node.send(column_name.to_sym))} "
}
}
end
indices = {}
set_left_and_rights = lambda do |node|
# set left
node[left_column_name] = indices[scope.call(node)] += 1
# find
where(["#{quoted_parent_column_full_name} = ? #{scope.call(node)}", node]).order("#{quoted_left_column_full_name}, #{quoted_right_column_full_name}, id").each{|n| set_left_and_rights.call(n) }
# set right
node[right_column_name] = indices[scope.call(node)] += 1
node.save!(:validate => validate_nodes)
end
# Find root node(s)
root_nodes = where("#{quoted_parent_column_full_name} IS NULL").order("#{quoted_left_column_full_name}, #{quoted_right_column_full_name}, id").each do |root_node|
# setup index for this scope
indices[scope.call(root_node)] ||= 0
set_left_and_rights.call(root_node)
end
end
end
# Iterates over tree elements and determines the current level in the tree.
# Only accepts default ordering, odering by an other column than lft
# does not work. This method is much more efficent than calling level
# because it doesn't require any additional database queries.
#
# Example:
# Category.each_with_level(Category.root.self_and_descendants) do |o, level|
#
def each_with_level(objects)
path = [nil]
objects.each do |o|
if o.parent_id != path.last
# we are on a new level, did we descend or ascend?
if path.include?(o.parent_id)
# remove wrong wrong tailing paths elements
path.pop while path.last != o.parent_id
else
path << o.parent_id
end
end
yield(o, path.length - 1)
end
end
# Same as each_with_level - Accepts a string as a second argument to sort the list
# Example:
# Category.each_with_level(Category.root.self_and_descendants, :sort_by_this_column) do |o, level|
def sorted_each_with_level(objects, order)
path = [nil]
children = []
objects.each do |o|
children << o if o.leaf?
if o.parent_id != path.last
if !children.empty? && !o.leaf?
children.sort_by! &order
children.each { |c| yield(c, path.length-1) }
children = []
end
# we are on a new level, did we decent or ascent?
if path.include?(o.parent_id)
# remove wrong wrong tailing paths elements
path.pop while path.last != o.parent_id
else
path << o.parent_id
end
end
yield(o,path.length-1) if !o.leaf?
end
if !children.empty?
children.sort_by! &order
children.each { |c| yield(c, path.length-1) }
end
end
def associate_parents(objects)
if objects.all?{|o| o.respond_to?(:association)}
id_indexed = objects.index_by(&:id)
objects.each do |object|
if !(association = object.association(:parent)).loaded? && (parent = id_indexed[object.parent_id])
association.target = parent
association.set_inverse_instance(parent)
end
end
else
objects
end
end
end
# Any instance method that returns a collection makes use of Rails 2.1's named_scope (which is bundled for Rails 2.0), so it can be treated as a finder.
#
# category.self_and_descendants.count
# category.ancestors.find(:all, :conditions => "name like '%foo%'")
# Value of the parent column
def parent_id
self[parent_column_name]
end
# Value of the left column
def left
self[left_column_name]
end
# Value of the right column
def right
self[right_column_name]
end
# Returns true if this is a root node.
def root?
parent_id.nil?
end
# Returns true if this is the end of a branch.
def leaf?
persisted? && right.to_i - left.to_i == 1
end
# Returns true is this is a child node
def child?
!root?
end
# Returns root
def root
if persisted?
self_and_ancestors.where(parent_column_name => nil).first
else
if parent_id && current_parent = nested_set_scope.find(parent_id)
current_parent.root
else
self
end
end
end
# Returns the array of all parents and self
def self_and_ancestors
nested_set_scope.where([
"#{quoted_left_column_full_name} <= ? AND #{quoted_right_column_full_name} >= ?", left, right
])
end
# Returns an array of all parents
def ancestors
without_self self_and_ancestors
end
# Returns the array of all children of the parent, including self
def self_and_siblings
nested_set_scope.where(parent_column_name => parent_id)
end
# Returns the array of all children of the parent, except self
def siblings
without_self self_and_siblings
end
# Returns a set of all of its nested children which do not have children
def leaves
descendants.where("#{quoted_right_column_full_name} - #{quoted_left_column_full_name} = 1")
end
# Returns the level of this object in the tree
# root level is 0
def level
parent_id.nil? ? 0 : compute_level
end
# Returns a set of itself and all of its nested children
def self_and_descendants
nested_set_scope.where([
"#{quoted_left_column_full_name} >= ? AND #{quoted_left_column_full_name} < ?", left, right
# using _left_ for both sides here lets us benefit from an index on that column if one exists
])
end
# Returns a set of all of its children and nested children
def descendants
without_self self_and_descendants
end
def is_descendant_of?(other)
other.left < self.left && self.left < other.right && same_scope?(other)
end
def is_or_is_descendant_of?(other)
other.left <= self.left && self.left < other.right && same_scope?(other)
end
def is_ancestor_of?(other)
self.left < other.left && other.left < self.right && same_scope?(other)
end
def is_or_is_ancestor_of?(other)
self.left <= other.left && other.left < self.right && same_scope?(other)
end
# Check if other model is in the same scope
def same_scope?(other)
Array(acts_as_nested_set_options[:scope]).all? do |attr|
self.send(attr) == other.send(attr)
end
end
# Find the first sibling to the left
def left_sibling
siblings.where(["#{quoted_left_column_full_name} < ?", left]).
order("#{quoted_left_column_full_name} DESC").last
end
# Find the first sibling to the right
def right_sibling
siblings.where(["#{quoted_left_column_full_name} > ?", left]).first
end
# Shorthand method for finding the left sibling and moving to the left of it.
def move_left
move_to_left_of left_sibling
end
# Shorthand method for finding the right sibling and moving to the right of it.
def move_right
move_to_right_of right_sibling
end
# Move the node to the left of another node (you can pass id only)
def move_to_left_of(node)
move_to node, :left
end
# Move the node to the left of another node (you can pass id only)
def move_to_right_of(node)
move_to node, :right
end
# Move the node to the child of another node (you can pass id only)
def move_to_child_of(node)
move_to node, :child
end
# Move the node to the child of another node with specify index (you can pass id only)
def move_to_child_with_index(node, index)
if node.children.empty?
move_to_child_of(node)
elsif node.children.count == index
move_to_right_of(node.children.last)
else
move_to_left_of(node.children[index])
end
end
# Move the node to root nodes
def move_to_root
move_to nil, :root
end
# Order children in a nested set by an attribute
# Can order by any attribute class that uses the Comparable mixin, for example a string or integer
# Usage example when sorting categories alphabetically: @new_category.move_to_ordered_child_of(@root, "name")
def move_to_ordered_child_of(parent, order_attribute, ascending = true)
self.move_to_root and return unless parent
left = nil # This is needed, at least for the tests.
parent.children.each do |n| # Find the node immediately to the left of this node.
if ascending
left = n if n.send(order_attribute) < self.send(order_attribute)
else
left = n if n.send(order_attribute) > self.send(order_attribute)
end
end
self.move_to_child_of(parent)
return unless parent.children.count > 1 # Only need to order if there are multiple children.
if left # Self has a left neighbor.
self.move_to_right_of(left)
else # Self is the left most node.
self.move_to_left_of(parent.children[0])
end
end
def move_possible?(target)
self != target && # Can't target self
same_scope?(target) && # can't be in different scopes
# !(left..right).include?(target.left..target.right) # this needs tested more
# detect impossible move
!((left <= target.left && right >= target.left) or (left <= target.right && right >= target.right))
end
def to_text
self_and_descendants.map do |node|
"#{'*'*(node.level+1)} #{node.id} #{node.to_s} (#{node.parent_id}, #{node.left}, #{node.right})"
end.join("\n")
end
protected
def compute_level
node, nesting = self, 0
while (association = node.association(:parent)).loaded? && association.target
nesting += 1
node = node.parent
end if node.respond_to? :association
node == self ? ancestors.count : node.level + nesting
end
def without_self(scope)
scope.where(["#{self.class.quoted_table_name}.#{self.class.primary_key} != ?", self])
end
# All nested set queries should use this nested_set_scope, which performs finds on
# the base ActiveRecord class, using the :scope declared in the acts_as_nested_set
# declaration.
def nested_set_scope(options = {})
options = {:order => quoted_left_column_full_name}.merge(options)
scopes = Array(acts_as_nested_set_options[:scope])
options[:conditions] = scopes.inject({}) do |conditions,attr|
conditions.merge attr => self[attr]
end unless scopes.empty?
self.class.base_class.unscoped.scoped options
end
def store_new_parent
@move_to_new_parent_id = send("#{parent_column_name}_changed?") ? parent_id : false
true # force callback to return true
end
def move_to_new_parent
if @move_to_new_parent_id.nil?
move_to_root
elsif @move_to_new_parent_id
move_to_child_of(@move_to_new_parent_id)
end
end
def set_depth!
if nested_set_scope.column_names.map(&:to_s).include?(depth_column_name.to_s)
in_tenacious_transaction do
reload
nested_set_scope.where(:id => id).update_all(["#{quoted_depth_column_name} = ?", level])
end
self[depth_column_name.to_sym] = self.level
end
end
# on creation, set automatically lft and rgt to the end of the tree
def set_default_left_and_right
highest_right_row = nested_set_scope(:order => "#{quoted_right_column_full_name} desc").limit(1).lock(true).first
maxright = highest_right_row ? (highest_right_row[right_column_name] || 0) : 0
# adds the new node to the right of all existing nodes
self[left_column_name] = maxright + 1
self[right_column_name] = maxright + 2
end
def in_tenacious_transaction(&block)
retry_count = 0
begin
transaction(&block)
rescue ActiveRecord::StatementInvalid => error
raise unless connection.open_transactions.zero?
raise unless error.message =~ /Deadlock found when trying to get lock|Lock wait timeout exceeded/
raise unless retry_count < 10
retry_count += 1
logger.info "Deadlock detected on retry #{retry_count}, restarting transaction"
sleep(rand(retry_count)*0.1) # Aloha protocol
retry
end
end
# Prunes a branch off of the tree, shifting all of the elements on the right
# back to the left so the counts still work.
def destroy_descendants
return if right.nil? || left.nil? || skip_before_destroy
in_tenacious_transaction do
reload_nested_set
# select the rows in the model that extend past the deletion point and apply a lock
nested_set_scope.where(["#{quoted_left_column_full_name} >= ?", left]).
select(id).lock(true)
if acts_as_nested_set_options[:dependent] == :destroy
descendants.each do |model|
model.skip_before_destroy = true
model.destroy
end
else
nested_set_scope.where(["#{quoted_left_column_name} > ? AND #{quoted_right_column_name} < ?", left, right]).
delete_all
end
# update lefts and rights for remaining nodes
diff = right - left + 1
nested_set_scope.where(["#{quoted_left_column_full_name} > ?", right]).update_all(
["#{quoted_left_column_name} = (#{quoted_left_column_name} - ?)", diff]
)
nested_set_scope.where(["#{quoted_right_column_full_name} > ?", right]).update_all(
["#{quoted_right_column_name} = (#{quoted_right_column_name} - ?)", diff]
)
# Don't allow multiple calls to destroy to corrupt the set
self.skip_before_destroy = true
end
end
# reload left, right, and parent
def reload_nested_set
reload(
:select => "#{quoted_left_column_full_name}, #{quoted_right_column_full_name}, #{quoted_parent_column_full_name}",
:lock => true
)
end
def move_to(target, position)
raise ActiveRecord::ActiveRecordError, "You cannot move a new node" if self.new_record?
run_callbacks :move do
in_tenacious_transaction do
if target.is_a? self.class.base_class
target.reload_nested_set
elsif position != :root
# load object if node is not an object
target = nested_set_scope.find(target)
end
self.reload_nested_set
unless position == :root || move_possible?(target)
raise ActiveRecord::ActiveRecordError, "Impossible move, target node cannot be inside moved tree."
end
bound = case position
when :child; target[right_column_name]
when :left; target[left_column_name]
when :right; target[right_column_name] + 1
when :root; 1
else raise ActiveRecord::ActiveRecordError, "Position should be :child, :left, :right or :root ('#{position}' received)."
end
if bound > self[right_column_name]
bound = bound - 1
other_bound = self[right_column_name] + 1
else
other_bound = self[left_column_name] - 1
end
# there would be no change
return if bound == self[right_column_name] || bound == self[left_column_name]
# we have defined the boundaries of two non-overlapping intervals,
# so sorting puts both the intervals and their boundaries in order
a, b, c, d = [self[left_column_name], self[right_column_name], bound, other_bound].sort
# select the rows in the model between a and d, and apply a lock
self.class.base_class.select('id').lock(true).where(
["#{quoted_left_column_full_name} >= :a and #{quoted_right_column_full_name} <= :d", {:a => a, :d => d}]
)
new_parent = case position
when :child; target.id
when :root; nil
else target[parent_column_name]
end
where_statement = ["not (#{quoted_left_column_name} = CASE " +
"WHEN #{quoted_left_column_name} BETWEEN :a AND :b " +
"THEN #{quoted_left_column_name} + :d - :b " +
"WHEN #{quoted_left_column_name} BETWEEN :c AND :d " +
"THEN #{quoted_left_column_name} + :a - :c " +
"ELSE #{quoted_left_column_name} END AND " +
"#{quoted_right_column_name} = CASE " +
"WHEN #{quoted_right_column_name} BETWEEN :a AND :b " +
"THEN #{quoted_right_column_name} + :d - :b " +
"WHEN #{quoted_right_column_name} BETWEEN :c AND :d " +
"THEN #{quoted_right_column_name} + :a - :c " +
"ELSE #{quoted_right_column_name} END AND " +
"#{quoted_parent_column_name} = CASE " +
"WHEN #{self.class.base_class.primary_key} = :id THEN :new_parent " +
"ELSE #{quoted_parent_column_name} END)" ,
{:a => a, :b => b, :c => c, :d => d, :id => self.id, :new_parent => new_parent} ]
self.nested_set_scope.where(*where_statement).update_all([
"#{quoted_left_column_name} = CASE " +
"WHEN #{quoted_left_column_name} BETWEEN :a AND :b " +
"THEN #{quoted_left_column_name} + :d - :b " +
"WHEN #{quoted_left_column_name} BETWEEN :c AND :d " +
"THEN #{quoted_left_column_name} + :a - :c " +
"ELSE #{quoted_left_column_name} END, " +
"#{quoted_right_column_name} = CASE " +
"WHEN #{quoted_right_column_name} BETWEEN :a AND :b " +
"THEN #{quoted_right_column_name} + :d - :b " +
"WHEN #{quoted_right_column_name} BETWEEN :c AND :d " +
"THEN #{quoted_right_column_name} + :a - :c " +
"ELSE #{quoted_right_column_name} END, " +
"#{quoted_parent_column_name} = CASE " +
"WHEN #{self.class.base_class.primary_key} = :id THEN :new_parent " +
"ELSE #{quoted_parent_column_name} END",
{:a => a, :b => b, :c => c, :d => d, :id => self.id, :new_parent => new_parent}
])
end
target.reload_nested_set if target
self.set_depth!
self.descendants.each(&:save)
self.reload_nested_set
end
end
end
# Mixed into both classes and instances to provide easy access to the column names
module Columns
def left_column_name
acts_as_nested_set_options[:left_column]
end
def right_column_name
acts_as_nested_set_options[:right_column]
end
def depth_column_name
acts_as_nested_set_options[:depth_column]
end
def parent_column_name
acts_as_nested_set_options[:parent_column]
end
def order_column
acts_as_nested_set_options[:order_column] || left_column_name
end
def scope_column_names
Array(acts_as_nested_set_options[:scope])
end
def quoted_left_column_name
connection.quote_column_name(left_column_name)
end
def quoted_right_column_name
connection.quote_column_name(right_column_name)
end
def quoted_depth_column_name
connection.quote_column_name(depth_column_name)
end
def quoted_parent_column_name
connection.quote_column_name(parent_column_name)
end
def quoted_scope_column_names
scope_column_names.collect {|column_name| connection.quote_column_name(column_name) }
end
def quoted_left_column_full_name
"#{quoted_table_name}.#{quoted_left_column_name}"
end
def quoted_right_column_full_name
"#{quoted_table_name}.#{quoted_right_column_name}"
end
def quoted_parent_column_full_name
"#{quoted_table_name}.#{quoted_parent_column_name}"
end
end
end
end
end

View File

@ -1,89 +0,0 @@
# -*- coding: utf-8 -*-
module CollectiveIdea #:nodoc:
module Acts #:nodoc:
module NestedSet #:nodoc:
# This module provides some helpers for the model classes using acts_as_nested_set.
# It is included by default in all views.
#
module Helper
# Returns options for select.
# You can exclude some items from the tree.
# You can pass a block receiving an item and returning the string displayed in the select.
#
# == Params
# * +class_or_item+ - Class name or top level times
# * +mover+ - The item that is being move, used to exlude impossible moves
# * +&block+ - a block that will be used to display: { |item| ... item.name }
#
# == Usage
#
# <%= f.select :parent_id, nested_set_options(Category, @category) {|i|
# "#{'' * i.level} #{i.name}"
# }) %>
#
def nested_set_options(class_or_item, mover = nil)
if class_or_item.is_a? Array
items = class_or_item.reject { |e| !e.root? }
else
class_or_item = class_or_item.roots if class_or_item.respond_to?(:scoped)
items = Array(class_or_item)
end
result = []
items.each do |root|
result += root.class.associate_parents(root.self_and_descendants).map do |i|
if mover.nil? || mover.new_record? || mover.move_possible?(i)
[yield(i), i.id]
end
end.compact
end
result
end
# Returns options for select as nested_set_options, sorted by an specific column
# It requires passing a string with the name of the column to sort the set with
# You can exclude some items from the tree.
# You can pass a block receiving an item and returning the string displayed in the select.
#
# == Params
# * +class_or_item+ - Class name or top level times
# * +:column+ - Column to sort the set (this will sort each children for all root elements)
# * +mover+ - The item that is being move, used to exlude impossible moves
# * +&block+ - a block that will be used to display: { |item| ... item.name }
#
# == Usage
#
# <%= f.select :parent_id, nested_set_options(Category, :sort_by_this_column, @category) {|i|
# "#{'' * i.level} #{i.name}"
# }) %>
#
def sorted_nested_set_options(class_or_item, order, mover = nil)
if class_or_item.is_a? Array
items = class_or_item.reject { |e| !e.root? }
else
class_or_item = class_or_item.roots if class_or_item.is_a?(Class)
items = Array(class_or_item)
end
result = []
children = []
items.each do |root|
root.class.associate_parents(root.self_and_descendants).map do |i|
if mover.nil? || mover.new_record? || mover.move_possible?(i)
if !i.leaf?
children.sort_by! &order
children.each { |c| result << [yield(c), c.id] }
children = []
result << [yield(i), i.id]
else
children << i
end
end
end.compact
end
children.sort_by! &order
children.each { |c| result << [yield(c), c.id] }
result
end
end
end
end
end

View File

@ -1,3 +0,0 @@
module AwesomeNestedSet
VERSION = '2.1.6' unless defined?(::AwesomeNestedSet::VERSION)
end

View File

@ -1,96 +0,0 @@
require 'spec_helper'
require 'awesome_nested_set/helper'
describe "Helper" do
include CollectiveIdea::Acts::NestedSet::Helper
before(:all) do
self.class.fixtures :categories
end
describe "nested_set_options" do
it "test_nested_set_options" do
expected = [
[" Top Level", 1],
["- Child 1", 2],
['- Child 2', 3],
['-- Child 2.1', 4],
['- Child 3', 5],
[" Top Level 2", 6]
]
actual = nested_set_options(Category.scoped) do |c|
"#{'-' * c.level} #{c.name}"
end
actual.should == expected
end
it "test_nested_set_options_with_mover" do
expected = [
[" Top Level", 1],
["- Child 1", 2],
['- Child 3', 5],
[" Top Level 2", 6]
]
actual = nested_set_options(Category.scoped, categories(:child_2)) do |c|
"#{'-' * c.level} #{c.name}"
end
actual.should == expected
end
it "test_nested_set_options_with_class_as_argument" do
expected = [
[" Top Level", 1],
["- Child 1", 2],
['- Child 2', 3],
['-- Child 2.1', 4],
['- Child 3', 5],
[" Top Level 2", 6]
]
actual = nested_set_options(Category) do |c|
"#{'-' * c.level} #{c.name}"
end
actual.should == expected
end
it "test_nested_set_options_with_class_as_argument_with_mover" do
expected = [
[" Top Level", 1],
["- Child 1", 2],
['- Child 3', 5],
[" Top Level 2", 6]
]
actual = nested_set_options(Category, categories(:child_2)) do |c|
"#{'-' * c.level} #{c.name}"
end
actual.should == expected
end
it "test_nested_set_options_with_array_as_argument_without_mover" do
expected = [
[" Top Level", 1],
["- Child 1", 2],
['- Child 2', 3],
['-- Child 2.1', 4],
['- Child 3', 5],
[" Top Level 2", 6]
]
actual = nested_set_options(Category.all) do |c|
"#{'-' * c.level} #{c.name}"
end
actual.should == expected
end
it "test_nested_set_options_with_array_as_argument_with_mover" do
expected = [
[" Top Level", 1],
["- Child 1", 2],
['- Child 3', 5],
[" Top Level 2", 6]
]
actual = nested_set_options(Category.all, categories(:child_2)) do |c|
"#{'-' * c.level} #{c.name}"
end
actual.should == expected
end
end
end

File diff suppressed because it is too large Load Diff

View File

@ -1,27 +0,0 @@
sqlite3:
adapter: <%= "jdbc" if defined? JRUBY_VERSION %>sqlite3
database: awesome_nested_set.sqlite3.db
sqlite3mem:
adapter: <%= "jdbc" if defined? JRUBY_VERSION %>sqlite3
database: ":memory:"
postgresql:
adapter: postgresql
encoding: unicode
database: awesome_nested_set_plugin_test
pool: 5
username: postgres
password: postgres
min_messages: warning
mysql:
adapter: mysql2
host: localhost
username: root
password:
database: awesome_nested_set_plugin_test
## Add DB Configuration to run Oracle tests
oracle:
adapter: oracle_enhanced
host: localhost
username: awesome_nested_set_dev
password:
database: xe

View File

@ -1,74 +0,0 @@
ActiveRecord::Schema.define(:version => 0) do
create_table :categories, :force => true do |t|
t.column :name, :string
t.column :parent_id, :integer
t.column :lft, :integer
t.column :rgt, :integer
t.column :depth, :integer
t.column :organization_id, :integer
end
create_table :departments, :force => true do |t|
t.column :name, :string
end
create_table :notes, :force => true do |t|
t.column :body, :text
t.column :parent_id, :integer
t.column :lft, :integer
t.column :rgt, :integer
t.column :depth, :integer
t.column :notable_id, :integer
t.column :notable_type, :string
end
create_table :renamed_columns, :force => true do |t|
t.column :name, :string
t.column :mother_id, :integer
t.column :red, :integer
t.column :black, :integer
t.column :pitch, :integer
end
create_table :things, :force => true do |t|
t.column :body, :text
t.column :parent_id, :integer
t.column :lft, :integer
t.column :rgt, :integer
t.column :depth, :integer
t.column :children_count, :integer
end
create_table :brokens, :force => true do |t|
t.column :name, :string
t.column :parent_id, :integer
t.column :lft, :integer
t.column :rgt, :integer
t.column :depth, :integer
end
create_table :orders, :force => true do |t|
t.column :name, :string
t.column :parent_id, :integer
t.column :lft, :integer
t.column :rgt, :integer
t.column :depth, :integer
end
create_table :positions, :force => true do |t|
t.column :name, :string
t.column :parent_id, :integer
t.column :lft, :integer
t.column :rgt, :integer
t.column :depth, :integer
t.column :position, :integer
end
create_table :no_depths, :force => true do |t|
t.column :name, :string
t.column :parent_id, :integer
t.column :lft, :integer
t.column :rgt, :integer
end
end

View File

@ -1,3 +0,0 @@
one:
id: 1
name: One

View File

@ -1,34 +0,0 @@
top_level:
id: 1
name: Top Level
lft: 1
rgt: 10
child_1:
id: 2
name: Child 1
parent_id: 1
lft: 2
rgt: 3
child_2:
id: 3
name: Child 2
parent_id: 1
lft: 4
rgt: 7
child_2_1:
id: 4
name: Child 2.1
parent_id: 3
lft: 5
rgt: 6
child_3:
id: 5
name: Child 3
parent_id: 1
lft: 8
rgt: 9
top_level_2:
id: 6
name: Top Level 2
lft: 11
rgt: 12

View File

@ -1,3 +0,0 @@
top:
id: 1
name: Top

View File

@ -1,38 +0,0 @@
scope1:
id: 1
body: Top Level
lft: 1
rgt: 10
notable_id: 1
notable_type: Category
child_1:
id: 2
body: Child 1
parent_id: 1
lft: 2
rgt: 3
notable_id: 1
notable_type: Category
child_2:
id: 3
body: Child 2
parent_id: 1
lft: 4
rgt: 7
notable_id: 1
notable_type: Category
child_3:
id: 4
body: Child 3
parent_id: 1
lft: 8
rgt: 9
notable_id: 1
notable_type: Category
scope2:
id: 5
body: Top Level 2
lft: 1
rgt: 2
notable_id: 1
notable_type: Departments

View File

@ -1,27 +0,0 @@
parent1:
id: 1
body: Top Level
lft: 1
rgt: 10
children_count: 2
child_1:
id: 2
body: Child 1
parent_id: 1
lft: 2
rgt: 3
children_count: 0
child_2:
id: 3
body: Child 2
parent_id: 1
lft: 4
rgt: 7
children_count: 0
child_2_1:
id: 4
body: Child 2.1
parent_id: 3
lft: 8
rgt: 9
children_count: 0

View File

@ -1,33 +0,0 @@
plugin_test_dir = File.dirname(__FILE__)
require 'rubygems'
require 'bundler/setup'
require 'logger'
require 'active_record'
ActiveRecord::Base.logger = Logger.new(plugin_test_dir + "/debug.log")
require 'yaml'
require 'erb'
ActiveRecord::Base.configurations = YAML::load(ERB.new(IO.read(plugin_test_dir + "/db/database.yml")).result)
ActiveRecord::Base.establish_connection(ENV["DB"] ||= "sqlite3mem")
ActiveRecord::Migration.verbose = false
require 'combustion/database'
Combustion::Database.create_database(ActiveRecord::Base.configurations[ENV["DB"]])
load(File.join(plugin_test_dir, "db", "schema.rb"))
require 'awesome_nested_set'
require 'support/models'
require 'action_controller'
require 'rspec/rails'
RSpec.configure do |config|
config.fixture_path = "#{plugin_test_dir}/fixtures"
config.use_transactional_fixtures = true
config.after(:suite) do
unless /sqlite/ === ENV['DB']
Combustion::Database.drop_database(ActiveRecord::Base.configurations[ENV['DB']])
end
end
end

View File

@ -1,96 +0,0 @@
class Note < ActiveRecord::Base
acts_as_nested_set :scope => [:notable_id, :notable_type]
end
class Default < ActiveRecord::Base
self.table_name = 'categories'
acts_as_nested_set
end
class ScopedCategory < ActiveRecord::Base
self.table_name = 'categories'
acts_as_nested_set :scope => :organization
end
class OrderedCategory < ActiveRecord::Base
self.table_name = 'categories'
acts_as_nested_set :order_column => 'name'
end
class RenamedColumns < ActiveRecord::Base
acts_as_nested_set :parent_column => 'mother_id',
:left_column => 'red',
:right_column => 'black',
:depth_column => 'pitch'
end
class Category < ActiveRecord::Base
acts_as_nested_set
validates_presence_of :name
# Setup a callback that we can switch to true or false per-test
set_callback :move, :before, :custom_before_move
cattr_accessor :test_allows_move
@@test_allows_move = true
def custom_before_move
@@test_allows_move
end
def to_s
name
end
def recurse &block
block.call self, lambda{
self.children.each do |child|
child.recurse &block
end
}
end
end
class Thing < ActiveRecord::Base
acts_as_nested_set :counter_cache => 'children_count'
end
class DefaultWithCallbacks < ActiveRecord::Base
self.table_name = 'categories'
attr_accessor :before_add, :after_add, :before_remove, :after_remove
acts_as_nested_set :before_add => :do_before_add_stuff,
:after_add => :do_after_add_stuff,
:before_remove => :do_before_remove_stuff,
:after_remove => :do_after_remove_stuff
private
[ :before_add, :after_add, :before_remove, :after_remove ].each do |hook_name|
define_method "do_#{hook_name}_stuff" do |child_node|
self.send("#{hook_name}=", child_node)
end
end
end
class Broken < ActiveRecord::Base
acts_as_nested_set
end
class Order < ActiveRecord::Base
acts_as_nested_set
default_scope order(:name)
end
class Position < ActiveRecord::Base
acts_as_nested_set
default_scope order(:position)
end
class NoDepth < ActiveRecord::Base
acts_as_nested_set
end