├── .gitignore ├── .travis.yml ├── Changelog.md ├── Gemfile ├── MIT-LICENSE ├── README.md ├── Rakefile ├── active_admin-sortable_tree.gemspec ├── app └── assets │ ├── javascripts │ └── active_admin │ │ └── sortable.js.coffee │ └── stylesheets │ └── active_admin │ └── sortable.sass ├── bin └── rails ├── docs ├── example.gif └── example.png ├── gemfiles ├── 4.2.gemfile ├── 5.0.gemfile ├── 5.1.gemfile └── 5.2.gemfile ├── lib ├── active_admin │ ├── sortable_tree.rb │ ├── sortable_tree │ │ ├── compatibility.rb │ │ ├── controller_actions.rb │ │ ├── engine.rb │ │ └── version.rb │ └── views │ │ ├── index_as_block_decorator.rb │ │ └── index_as_sortable.rb └── activeadmin-sortable-tree.rb ├── script └── rails ├── spec ├── dummy │ ├── README.rdoc │ ├── Rakefile │ ├── app │ │ ├── admin │ │ │ ├── category.rb │ │ │ ├── category_sort_disabled.rb │ │ │ ├── category_tree.rb │ │ │ └── dashboard.rb │ │ ├── assets │ │ │ ├── javascripts │ │ │ │ ├── active_admin.js │ │ │ │ ├── application.js │ │ │ │ └── jquery.simulate.js │ │ │ └── stylesheets │ │ │ │ ├── active_admin.css.scss │ │ │ │ └── application.css │ │ ├── controllers │ │ │ └── application_controller.rb │ │ ├── helpers │ │ │ └── application_helper.rb │ │ ├── mailers │ │ │ └── .gitkeep │ │ ├── models │ │ │ ├── .gitkeep │ │ │ ├── admin_user.rb │ │ │ └── category.rb │ │ └── views │ │ │ └── layouts │ │ │ └── application.html.erb │ ├── config.ru │ ├── config │ │ ├── application.rb │ │ ├── boot.rb │ │ ├── database.yml │ │ ├── environment.rb │ │ ├── environments │ │ │ ├── development.rb │ │ │ ├── production.rb │ │ │ └── test.rb │ │ ├── initializers │ │ │ ├── active_admin.rb │ │ │ ├── backtrace_silencers.rb │ │ │ ├── devise.rb │ │ │ ├── inflections.rb │ │ │ ├── mime_types.rb │ │ │ ├── secret_token.rb │ │ │ ├── session_store.rb │ │ │ └── wrap_parameters.rb │ │ ├── locales │ │ │ ├── devise.en.yml │ │ │ └── en.yml │ │ └── routes.rb │ ├── db │ │ ├── migrate │ │ │ ├── 20140806024135_devise_create_admin_users.rb │ │ │ ├── 20140806024139_create_active_admin_comments.rb │ │ │ └── 20140806032156_create_categories.rb │ │ ├── schema.rb │ │ └── seeds.rb │ ├── lib │ │ └── assets │ │ │ └── .gitkeep │ ├── log │ │ └── .gitkeep │ ├── public │ │ ├── 404.html │ │ ├── 422.html │ │ ├── 500.html │ │ └── favicon.ico │ └── script │ │ └── rails ├── features │ └── sortable_spec.rb ├── rails_helper.rb ├── spec_helper.rb └── support │ └── wait_for_ajax.rb └── vendor └── assets └── javascripts └── jquery.mjs.nestedSortable.js /.gitignore: -------------------------------------------------------------------------------- 1 | .rspec 2 | .bundle/ 3 | log/*.log 4 | pkg/ 5 | spec/dummy/db/*.sqlite3 6 | spec/dummy/log/*.log 7 | spec/dummy/tmp/ 8 | spec/dummy/public/assets 9 | spec/dummy/.sass-cache 10 | vendor/bundle 11 | Gemfile.lock 12 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | language: ruby 2 | 3 | before_install: 4 | # Workaround for https://github.com/travis-ci/travis-ci/issues/8969 5 | - gem update --system 6 | 7 | rvm: 8 | - 2.2 9 | - 2.3 10 | - 2.4 11 | - 2.5 12 | - 2.6 13 | 14 | env: 15 | - RAILS_VERSION=4.2 16 | - RAILS_VERSION=5.0 17 | - RAILS_VERSION=5.1 18 | - RAILS_VERSION=5.2 19 | 20 | matrix: 21 | exclude: 22 | - rvm: 2.2 23 | env: RAILS_VERSION=5.0 24 | - rvm: 2.2 25 | env: RAILS_VERSION=5.1 26 | - rvm: 2.2 27 | env: RAILS_VERSION=5.2 28 | - rvm: 2.5 29 | env: RAILS_VERSION=4.2 30 | - rvm: 2.5 31 | env: RAILS_VERSION=5.0 32 | - rvm: 2.6 33 | env: RAILS_VERSION=4.2 34 | - rvm: 2.6 35 | env: RAILS_VERSION=5.0 36 | 37 | sudo: false 38 | -------------------------------------------------------------------------------- /Changelog.md: -------------------------------------------------------------------------------- 1 | # Change Log 2 | 3 | All notable changes to this project will be documented in this file. 4 | 5 | ## [2.1.0] - 2020-03-11 6 | 7 | ### Added 8 | 9 | - A config to opt out of registering assets (see #81) 10 | - Support for UUID primary keys (see #85) 11 | 12 | ## [2.0.0] - 2018-01-22 13 | 14 | ### Changed 15 | 16 | - Depend on same version of `jquery-ui-rails` as ActiveAdmin 17 | - Update dependencies to only support ActiveAdmin `< 1.1.0` because `v1.1.0` 18 | [dropped its dependency on `jquery-ui-rails`](https://github.com/activeadmin/activeadmin/blob/master/CHANGELOG.md). 19 | - Remove usage of bourbon mixin; instead rely on ActiveAdmin's utilities mixin 20 | (fixes #73) 21 | 22 | ### Removed 23 | 24 | - Remove support for Rails 3.2 25 | - Remove support for ActiveAdmin 0.6.6 26 | 27 | ### Upgrading from 1.0.0 28 | 29 | It is suggested (but not required) to manually include the JavaScript and 30 | stylesheet to your manifest files in preparation for ActiveAdmin v2.0. See the 31 | Installation section of the [README.md](README.md#installation) for instructions. 32 | 33 | ## [1.0.0] - 2017-06-01 34 | 35 | ### Added 36 | 37 | - Support for Rails 5.0 and 5.1 by conditionally invoking `parameterize` with its 38 | expected parameters. 39 | 40 | ### Changed 41 | 42 | - Relax dependency on `jquery-ui-rails` to be `>= 5.0` (previously `~> 5.0`). 43 | 44 | ### Removed 45 | 46 | - Ruby 1.9.3, 2.1, and 2.2 are no longer explicitly supported. 47 | 48 | ## [0.3.0] - 2016-09-08 49 | 50 | - Rename sortable.css.sass to sortable.sass to fix deprecation warnings 51 | - Update usage of box-sizing to fix Bourbon deprecation warning 52 | 53 | ## [0.2.1] - 2015-04-15 54 | 55 | - Suppress list styles on sortable indexes when batch actions are disabled. 56 | ([#48](https://github.com/zorab47/activeadmin-sortable-tree/issues/48)). 57 | - Do not render the extra cell for batch actions when they are disabled, which 58 | removes extra whitespace to the left of items. 59 | 60 | ## [0.2.0] - 2014-12-23 61 | 62 | - Shrink gem file size by excluding spec files and dummy application. 63 | 64 | ## [0.1.0] - 2014-11-19 65 | 66 | - Add option to disable sorting: `sortable: false`, which causes the index view 67 | to be a static tree view. 68 | - Ensure the default actions honor authorization checks 69 | ([#43](https://github.com/nebirhos/activeadmin-sortable-tree/pull/43)). 70 | 71 | ## 0.0.1 - 2014-08-07 72 | 73 | - Published to Rubygems. 74 | 75 | 76 | [unreleased]: https://github.com/zorab47/active_admin-sortable_tree/compare/v1.0.0...HEAD 77 | [0.1.0]: https://github.com/zorab47/active_admin-sortable_tree/compare/v0.0.1...v0.1.0 78 | [0.2.0]: https://github.com/zorab47/active_admin-sortable_tree/compare/v0.1.0...v0.2.0 79 | [0.2.1]: https://github.com/zorab47/active_admin-sortable_tree/compare/v0.2.0...v0.2.1 80 | [0.3.0]: https://github.com/zorab47/active_admin-sortable_tree/compare/v0.2.1...v0.3.0 81 | [1.0.0]: https://github.com/zorab47/active_admin-sortable_tree/compare/v0.3.0...v1.0.0 82 | [1.1.0]: https://github.com/zorab47/active_admin-sortable_tree/compare/v1.0.0...v1.1.0 83 | [2.0.0]: https://github.com/zorab47/active_admin-sortable_tree/compare/v1.1.0...v2.0.0 84 | [2.1.0]: https://github.com/zorab47/active_admin-sortable_tree/compare/v2.0.0...v2.1.0 85 | -------------------------------------------------------------------------------- /Gemfile: -------------------------------------------------------------------------------- 1 | source "http://rubygems.org" 2 | 3 | # Declare your gem's dependencies in activeadmin-tree.gemspec. 4 | # Bundler will treat runtime dependencies like base dependencies, and 5 | # development dependencies will be added by default to the :development group. 6 | gemspec 7 | 8 | version = ENV['RAILS_VERSION'] || "4.0" 9 | 10 | eval_gemfile File.expand_path("../gemfiles/#{version}.gemfile", __FILE__) 11 | -------------------------------------------------------------------------------- /MIT-LICENSE: -------------------------------------------------------------------------------- 1 | Copyright 2012 YOURNAME 2 | 3 | Permission is hereby granted, free of charge, to any person obtaining 4 | a copy of this software and associated documentation files (the 5 | "Software"), to deal in the Software without restriction, including 6 | without limitation the rights to use, copy, modify, merge, publish, 7 | distribute, sublicense, and/or sell copies of the Software, and to 8 | permit persons to whom the Software is furnished to do so, subject to 9 | the following conditions: 10 | 11 | The above copyright notice and this permission notice shall be 12 | included in all copies or substantial portions of the Software. 13 | 14 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, 15 | EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF 16 | MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND 17 | NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE 18 | LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION 19 | OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION 20 | WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 21 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # ActiveAdmin::SortableTree 2 | 3 | [![Gem Version](https://badge.fury.io/rb/active_admin-sortable_tree.svg)](http://badge.fury.io/rb/active_admin-sortable_tree) 4 | [![Build Status](https://travis-ci.org/zorab47/active_admin-sortable_tree.svg?branch=master)](https://travis-ci.org/zorab47/active_admin-sortable_tree) 5 | 6 | This gem adds a tree and a list view to your ActiveAdmin resource index, both 7 | sortable via drag'n'drop. 8 | 9 | ![ActiveAdmin::SortableTree Example](docs/example.gif) 10 | 11 | ## Installation 12 | 13 | 1. Add SortableTree to your Gemfile; then `bundle install` 14 | ```ruby 15 | gem "active_admin-sortable_tree", "~> 2.0.0" 16 | ``` 17 | 18 | 2. Add a require to your JavaScript manifest `app/assets/javascripts/active_admin.js` 19 | 20 | ```javascript 21 | //= require active_admin/sortable 22 | ``` 23 | 24 | 3. Add an import in your stylesheet manifest `app/assets/stylesheets/active_admin.scss` 25 | 26 | ```scss 27 | @import "active_admin/sortable"; 28 | ``` 29 | 30 | ## Usage (Tree) 31 | 32 | **Admin**: 33 | 34 | ```ruby 35 | # app/admin/page.rb 36 | ActiveAdmin.register Page do 37 | sortable tree: true 38 | 39 | index :as => :sortable do 40 | label :title # item content 41 | actions 42 | end 43 | end 44 | ``` 45 | 46 | **Model**: ActiveAdmin::SortableTree is agnostic to the tree implementation. All 47 | you have to do is expose a sorting attribute and a few tree methods (`:parent`, 48 | `:children` and `:roots`). Let's say you use 49 | [Ancestry](https://github.com/stefankroes/ancestry): 50 | 51 | ```ruby 52 | class Page < ActiveRecord::Base 53 | attr_accessible :title, :body, :position 54 | has_ancestry :orphan_strategy => :rootify 55 | end 56 | ``` 57 | 58 | You can configure these methods if you need: 59 | 60 | ```ruby 61 | ActiveAdmin.register Page do 62 | sortable tree: true, 63 | sorting_attribute: :position, 64 | parent_method: :parent, 65 | children_method: :children, 66 | roots_method: :roots, 67 | roots_collection: proc { current_user.pages.roots } 68 | # … 69 | end 70 | ``` 71 | 72 | The option `roots_collection` provides full control on how to find the root 73 | nodes of your sortable tree and is evaluated within the context of the 74 | controller. Please note that `roots_collection` will override what is specified 75 | in `roots_method`. 76 | 77 | ## Usage (List) 78 | 79 | **Admin**: 80 | 81 | ```ruby 82 | # app/admin/page.rb 83 | ActiveAdmin.register Page do 84 | sortable 85 | 86 | index :as => :sortable do 87 | label :title # item content 88 | actions 89 | end 90 | end 91 | ``` 92 | 93 | **Model**: Sortable list assumes you have a `:position` field in your resource. 94 | Of course it's configurable: 95 | 96 | ```ruby 97 | ActiveAdmin.register Page do 98 | sortable tree: false, # default 99 | sorting_attribute: :my_position_field 100 | # … 101 | end 102 | ``` 103 | 104 | **Note**: If you are using the [acts_as_list](https://github.com/swanandp/acts_as_list) gem to manage a `:position` field (not required, but allows for other nice programmatic manipulation of ordered model lists), you must ensure a zero-based index for your list using the `top_of_list` option: 105 | 106 | ```ruby 107 | class Page < ActiveRecord::Base 108 | # Make this list act like a zero-indexed array to avoid off-by-one errors in your sorting 109 | acts_as_list top_of_list: 0 110 | end 111 | ``` 112 | 113 | 114 | ## Usage (generic ActiveAdmin index) 115 | 116 | Currently supports only IndexAsBlock, more to come! 117 | 118 | **Admin**: 119 | ```ruby 120 | # app/admin/page.rb 121 | ActiveAdmin.register Page do 122 | sortable 123 | 124 | index :as => :block do |page| 125 | # item content 126 | end 127 | end 128 | ``` 129 | 130 | **Model**: Same as list view (see above) 131 | 132 | ## Customization 133 | 134 | ### Full options list with defaults 135 | 136 | ```ruby 137 | ActiveAdmin.register Page do 138 | sortable tree: true, 139 | max_levels: 0, # infinite indent levels 140 | protect_root: false, # allow root items to be dragged 141 | sorting_attribute: :position, 142 | parent_method: :parent, 143 | children_method: :children, 144 | roots_method: :roots, 145 | roots_collection: nil, # proc to specifiy retrieval of roots 146 | sortable: true, # Disable sorting (use only 'tree' functionality) 147 | collapsible: false, # show +/- buttons to collapse children 148 | start_collapsed: false, # when collapsible, start with all roots collapsed 149 | end 150 | ``` 151 | 152 | 153 | ### Actions 154 | 155 | In `IndexAsSortable` you can add custom actions (with or without the defaults): 156 | 157 | ```ruby 158 | index :as => :sortable do 159 | actions defaults: false do |page| 160 | link_to "Custom action", my_custom_path(page) 161 | end 162 | end 163 | ``` 164 | 165 | ### Ajax Callback Config 166 | 167 | It exposes three Ajax Events: ajaxDone, ajaxFail and ajaxAlways, which 168 | correspond to jQuery ajax callbacks: done, fail and always. 169 | 170 | To subscribe Ajax callback: 171 | 172 | ```javascript 173 | ActiveAdminSortableEvent.add('ajaxDone', function (){ 174 | // do what you want 175 | }) 176 | ``` 177 | 178 | ### Upgrading to SortableTree 2.0 from 1.0 179 | 180 | Upgrading from SortableTree 1.x requires manually specifying assets in your 181 | `app/assets/javascripts/active_admin.js` and `app/assets/stylesheets/active_admin.scss` 182 | files. 183 | 184 | 185 | ### Dependencies 186 | 187 | ActiveAdmin::SortableTree 2.0 supports ActiveAdmin 1.0.0+. For previous versions 188 | of ActiveAdmin use older SortableTree versions from the 1.x branch. 189 | 190 | Note: If you experience issues with drag and drop capability, you may need to 191 | specify the version for your ActiveAdmin installation. It is reported working 192 | using v0.6.6, or if you are using v1.0.0.pre, it is reported working on this 193 | commit [b3a9f4b](https://github.com/activeadmin/activeadmin/commit/b3a9f4b3e4051447d011c59649a73f876989a199) 194 | or later. 195 | 196 | ```ruby 197 | # Gemfile 198 | gem 'activeadmin', github: 'activeadmin', ref: 'b3a9f4b' 199 | ``` 200 | 201 | ### Suppressing warnings from Active Admin 202 | 203 | As of Active Admin 1.1.0, `config.register_stylesheet` and `config.register_javascript` have been deprecated. `ActiveAdmin::SortableTree` uses these interfaces to register required assets automatically. Because of this, you may see a deprecation warning: 204 | 205 | ``` 206 | DEPRECATION WARNING: Active Admin: The `register_javascript` config is deprecated and will be removed 207 | in v2. Import your "active_admin/sortable.js" javascript in the active_admin.js. 208 | (called from
at config/environment.rb:5) 209 | ``` 210 | 211 | You could opt out of it by setting `config.aa_sortable_tree.register_assets` to `false`: 212 | 213 | ```ruby 214 | # config/application.rb 215 | config.aa_sortable_tree.register_assets = false 216 | ``` 217 | 218 | ## Semantic Versioning 219 | 220 | ActiveAdmin::SortableTree follows [semantic versioning](http://semver.org). 221 | 222 | ## Alternatives 223 | 224 | - [Active Admin Sortable](https://github.com/neo/activeadmin-sortable) 225 | 226 | ## Copyright 227 | 228 | Copyright © 2013 Francesco Disperati, Cantiere Creativo. See the file 229 | MIT-LICENSE for details. See the full list list of 230 | [contributors](http://github.com/zorab47/active_admin-sortable_tree/graphs/contributors). 231 | -------------------------------------------------------------------------------- /Rakefile: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env rake 2 | begin 3 | require 'bundler/setup' 4 | rescue LoadError 5 | puts 'You must `gem install bundler` and `bundle install` to run rake tasks' 6 | end 7 | begin 8 | require 'rdoc/task' 9 | rescue LoadError 10 | require 'rdoc/rdoc' 11 | require 'rake/rdoctask' 12 | RDoc::Task = Rake::RDocTask 13 | end 14 | 15 | ENV['RAILS_VERSION'] ||= '4.0' 16 | 17 | RDoc::Task.new(:rdoc) do |rdoc| 18 | rdoc.rdoc_dir = 'rdoc' 19 | rdoc.title = 'ActiveAdmin::SortableTree' 20 | rdoc.options << '--line-numbers' 21 | rdoc.rdoc_files.include('README.rdoc') 22 | rdoc.rdoc_files.include('lib/**/*.rb') 23 | end 24 | 25 | 26 | Bundler::GemHelper.install_tasks 27 | 28 | require 'rspec/core/rake_task' 29 | RSpec::Core::RakeTask.new(:spec) 30 | task default: ['dummy:prepare', :spec] 31 | 32 | require 'rake/clean' 33 | CLEAN.include 'spec/dummy/db/*sqlite3', 'spec/dummy/log/*', 'spec/dummy/public/assets/*', 'spec/dummy/tmp/**/*' 34 | 35 | namespace :dummy do 36 | desc 'Setup dummy app database' 37 | task :prepare do 38 | # File.expand_path is executed directory of generated Rails app 39 | rakefile = File.expand_path('Rakefile', dummy_path) 40 | command = "rake -f '%s' db:schema:load RAILS_ENV=test" % rakefile 41 | sh(command) unless ENV["DISABLE_CREATE"] 42 | end 43 | 44 | # task :migrate do 45 | # # File.expand_path is executed directory of generated Rails app 46 | # rakefile = File.expand_path('Rakefile', dummy_path) 47 | # command = "rake -f '%s' db:migrate db:test:prepare" % rakefile 48 | # sh(command) unless ENV["DISABLE_MIGRATE"] 49 | # end 50 | 51 | def dummy_path 52 | rel_path = ENV['DUMMY_APP_PATH'] || 'spec/dummy' 53 | if @current_path.to_s.include?(rel_path) 54 | @current_path 55 | else 56 | @current_path = File.expand_path(rel_path) 57 | end 58 | end 59 | end 60 | -------------------------------------------------------------------------------- /active_admin-sortable_tree.gemspec: -------------------------------------------------------------------------------- 1 | $:.push File.expand_path("../lib", __FILE__) 2 | 3 | # Maintain your gem's version: 4 | require "active_admin/sortable_tree/version" 5 | 6 | # Describe your gem and declare its dependencies: 7 | Gem::Specification.new do |s| 8 | s.name = "active_admin-sortable_tree" 9 | s.version = ActiveAdmin::SortableTree::VERSION 10 | s.authors = ["Francesco Disperati", 'Charles Maresh'] 11 | s.email = ["me@nebirhos.com", 'zorab47@gmail.com'] 12 | s.homepage = "https://github.com/zorab47/active_admin-sortable_tree" 13 | s.summary = "Add drag and drop sorting to ActiveAdmin resources" 14 | s.description = "SortableTree provides sorting of lists and hierarchies from ActiveAdmin index views." 15 | s.license = "MIT" 16 | 17 | s.files = `git ls-files app lib vendor`.split($\) + ["Changelog.md", "README.md", "MIT-LICENSE"] 18 | 19 | s.add_dependency 'activeadmin', '>= 1.1' 20 | s.add_dependency 'coffee-rails' 21 | s.add_dependency 'jquery-rails' 22 | s.add_dependency 'sass', '~> 3.1' 23 | 24 | s.add_development_dependency 'capybara' 25 | s.add_development_dependency 'rspec-rails' 26 | s.add_development_dependency 'phantomjs' 27 | s.add_development_dependency 'poltergeist' 28 | s.add_development_dependency 'database_cleaner' 29 | end 30 | -------------------------------------------------------------------------------- /app/assets/javascripts/active_admin/sortable.js.coffee: -------------------------------------------------------------------------------- 1 | #= require jquery-ui/widgets/sortable 2 | #= require jquery.mjs.nestedSortable 3 | 4 | window.ActiveAdminSortableEvent = do -> 5 | eventToListeners = {} 6 | 7 | return { 8 | add: (event, callback) -> 9 | if not eventToListeners.hasOwnProperty(event) 10 | eventToListeners[event] = [] 11 | eventToListeners[event].push(callback) 12 | 13 | trigger: (event, args) -> 14 | if eventToListeners.hasOwnProperty(event) 15 | for callback in eventToListeners[event] 16 | try 17 | callback.call(null, args) 18 | catch e 19 | console.error(e) if console and console.error 20 | } 21 | 22 | $ -> 23 | $('.disclose').bind 'click', (event) -> 24 | $(this).closest('li').toggleClass('mjs-nestedSortable-collapsed').toggleClass('mjs-nestedSortable-expanded') 25 | 26 | $(".index_as_sortable [data-sortable-type]").each -> 27 | $this = $(@) 28 | 29 | if $this.data('sortable-type') == "tree" 30 | max_levels = $this.data('max-levels') 31 | tab_hack = 20 # nestedSortable default 32 | else 33 | max_levels = 1 34 | tab_hack = 99999 35 | 36 | $this.nestedSortable 37 | forcePlaceholderSize: true 38 | forceHelperSizeType: true 39 | errorClass: 'cantdoit' 40 | disableNesting: 'cantdoit' 41 | handle: '> .item' 42 | listType: 'ol' 43 | items: 'li' 44 | opacity: .6 45 | placeholder: 'placeholder' 46 | revert: 250 47 | maxLevels: max_levels, 48 | tabSize: tab_hack 49 | protectRoot: $this.data('protect-root') 50 | # prevent drag flickers 51 | tolerance: 'pointer' 52 | toleranceElement: '> div' 53 | isTree: true 54 | startCollapsed: $this.data("start-collapsed") 55 | update: -> 56 | $this.nestedSortable("disable") 57 | $.ajax 58 | url: $this.data("sortable-url") 59 | type: "post" 60 | data: $this.nestedSortable("serialize") 61 | .always -> 62 | $this.find('.item').each (index) -> 63 | if index % 2 64 | $(this).removeClass('odd').addClass('even') 65 | else 66 | $(this).removeClass('even').addClass('odd') 67 | $this.nestedSortable("enable") 68 | ActiveAdminSortableEvent.trigger('ajaxAlways') 69 | .done -> 70 | ActiveAdminSortableEvent.trigger('ajaxDone') 71 | .fail -> 72 | ActiveAdminSortableEvent.trigger('ajaxFail') 73 | -------------------------------------------------------------------------------- /app/assets/stylesheets/active_admin/sortable.sass: -------------------------------------------------------------------------------- 1 | $cOddRowBackground: #f4f5f5 2 | $cRowBorder: #e8e8e8 3 | $cRowSelected: #d9e4ec 4 | $cRowError: rgb(255,87,87) 5 | 6 | @import "active_admin/mixins/utilities" 7 | 8 | body.active_admin 9 | .disclose 10 | cursor: pointer 11 | width: 10px 12 | display: none 13 | 14 | .index_as_sortable 15 | .resource_selection_toggle_panel 16 | padding-left: 12px 17 | 18 | > ol 19 | margin: 16px 0 20 | 21 | ol 22 | list-style-type: none 23 | padding: 0 24 | 25 | li 26 | cursor: default !important 27 | 28 | &.placeholder 29 | height: 3em 30 | background: lighten($cOddRowBackground, 10%) 31 | border: 1px dashed $cRowSelected 32 | box-sizing: border-box 33 | 34 | &.cantdoit 35 | border: 1px dashed $cRowError 36 | 37 | .item 38 | width: 100% 39 | border-top: 1px solid $cRowBorder 40 | border-bottom: 1px solid $cRowBorder 41 | +clearfix 42 | 43 | &.even 44 | background: white 45 | 46 | &.odd 47 | background: $cOddRowBackground 48 | 49 | .cell 50 | margin: 0 51 | padding: 10px 12px 8px 12px 52 | 53 | h3.cell 54 | font-size: 16px 55 | line-height: 14px 56 | color: black 57 | 58 | &.ui-sortable 59 | li .item:hover 60 | cursor: move 61 | background-color: $cRowSelected 62 | 63 | > li > ol 64 | margin-left: 30px 65 | 66 | li.mjs-nestedSortable-collapsed > ol 67 | display: none 68 | 69 | li.mjs-nestedSortable-branch > div > .disclose 70 | display: block 71 | float: left 72 | padding: 10px 5px 8px 5px 73 | 74 | li.mjs-nestedSortable-collapsed > div > .disclose > span:before 75 | content: '+ ' 76 | 77 | li.mjs-nestedSortable-expanded > div > .disclose > span:before 78 | content: '- ' 79 | -------------------------------------------------------------------------------- /bin/rails: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env ruby 2 | 3 | ENGINE_ROOT = File.expand_path('../..', __FILE__) 4 | ENGINE_PATH = File.expand_path('../../lib/active_admin/sortable_tree/engine', __FILE__) 5 | 6 | # Set up gems listed in the Gemfile. 7 | ENV['BUNDLE_GEMFILE'] ||= File.expand_path('../../Gemfile', __FILE__) 8 | require 'bundler/setup' if File.exist?(ENV['BUNDLE_GEMFILE']) 9 | 10 | require 'rails/all' 11 | require 'rails/engine/commands' 12 | -------------------------------------------------------------------------------- /docs/example.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/zorab47/active_admin-sortable_tree/7f2b0fb7f407a526265182303da67a4457c05c31/docs/example.gif -------------------------------------------------------------------------------- /docs/example.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/zorab47/active_admin-sortable_tree/7f2b0fb7f407a526265182303da67a4457c05c31/docs/example.png -------------------------------------------------------------------------------- /gemfiles/4.2.gemfile: -------------------------------------------------------------------------------- 1 | gem 'puma' 2 | gem 'jquery-rails' 3 | gem 'jquery-ui-rails' 4 | gem 'ancestry' 5 | gem 'sqlite3', '~> 1.3.6' 6 | 7 | gem 'activeadmin' 8 | gem 'devise' 9 | gem 'rails', '~> 4.2.0' 10 | gem 'sass-rails' 11 | 12 | # vim: ft=ruby 13 | -------------------------------------------------------------------------------- /gemfiles/5.0.gemfile: -------------------------------------------------------------------------------- 1 | gem 'puma' 2 | gem 'jquery-rails' 3 | gem 'jquery-ui-rails' 4 | gem 'ancestry' 5 | gem 'sqlite3', '~> 1.3.6' 6 | 7 | gem 'activeadmin' 8 | gem 'devise' 9 | gem 'rails', '~> 5.0.0' 10 | gem 'sass-rails' 11 | 12 | # vim: ft=ruby 13 | -------------------------------------------------------------------------------- /gemfiles/5.1.gemfile: -------------------------------------------------------------------------------- 1 | gem 'puma' 2 | gem 'jquery-rails' 3 | gem 'jquery-ui-rails' 4 | gem 'ancestry' 5 | gem 'sqlite3', '~> 1.3.6' 6 | 7 | gem 'activeadmin' 8 | gem 'devise' 9 | gem 'rails', '~> 5.1.0' 10 | gem 'sass-rails' 11 | 12 | # vim: ft=ruby 13 | -------------------------------------------------------------------------------- /gemfiles/5.2.gemfile: -------------------------------------------------------------------------------- 1 | gem 'puma' 2 | gem 'jquery-rails' 3 | gem 'jquery-ui-rails' 4 | gem 'ancestry' 5 | gem 'sqlite3', '~> 1.3.6' 6 | 7 | gem 'activeadmin' 8 | gem 'devise' 9 | gem 'rails', '~> 5.2.0' 10 | gem 'sass-rails' 11 | 12 | # vim: ft=ruby 13 | -------------------------------------------------------------------------------- /lib/active_admin/sortable_tree.rb: -------------------------------------------------------------------------------- 1 | require 'activeadmin' 2 | 3 | require 'active_admin/sortable_tree/compatibility' 4 | require 'active_admin/sortable_tree/engine' 5 | require 'active_admin/sortable_tree/controller_actions' 6 | require 'active_admin/views/index_as_sortable' 7 | require 'active_admin/views/index_as_block_decorator' 8 | -------------------------------------------------------------------------------- /lib/active_admin/sortable_tree/compatibility.rb: -------------------------------------------------------------------------------- 1 | module ActiveAdmin::SortableTree 2 | class Compatibility 3 | def self.normalized_resource_name(resource_name) 4 | if Rails::VERSION::MAJOR >= 5 5 | resource_name.to_s.underscore.parameterize(separator: "_".freeze) 6 | else 7 | resource_name.to_s.underscore.parameterize("_".freeze) 8 | end 9 | end 10 | end 11 | end 12 | -------------------------------------------------------------------------------- /lib/active_admin/sortable_tree/controller_actions.rb: -------------------------------------------------------------------------------- 1 | module ActiveAdmin::SortableTree 2 | module ControllerActions 3 | 4 | attr_accessor :sortable_options 5 | 6 | def sortable(options = {}) 7 | options.reverse_merge! :sorting_attribute => :position, 8 | :parent_method => :parent, 9 | :children_method => :children, 10 | :roots_method => :roots, 11 | :tree => false, 12 | :max_levels => 0, 13 | :protect_root => false, 14 | :collapsible => false, #hides +/- buttons 15 | :start_collapsed => false, 16 | :sortable => true 17 | 18 | # BAD BAD BAD FIXME: don't pollute original class 19 | @sortable_options = options 20 | 21 | # disable pagination 22 | config.paginate = false 23 | 24 | collection_action :sort, :method => :post do 25 | resource_name = ActiveAdmin::SortableTree::Compatibility.normalized_resource_name(active_admin_config.resource_name) 26 | 27 | records = [] 28 | params[resource_name].each_pair do |resource, parent_resource| 29 | parent_resource = resource_class.find(parent_resource) rescue nil 30 | records << [resource_class.find(resource), parent_resource] 31 | end 32 | 33 | errors = [] 34 | ActiveRecord::Base.transaction do 35 | records.each_with_index do |(record, parent_record), position| 36 | record.send "#{options[:sorting_attribute]}=", position 37 | if options[:tree] 38 | record.send "#{options[:parent_method]}=", parent_record 39 | end 40 | errors << {record.id => record.errors} if !record.save 41 | end 42 | end 43 | if errors.empty? 44 | head 200 45 | else 46 | render json: errors, status: 422 47 | end 48 | end 49 | 50 | end 51 | 52 | end 53 | 54 | ::ActiveAdmin::ResourceDSL.send(:include, ControllerActions) 55 | end 56 | -------------------------------------------------------------------------------- /lib/active_admin/sortable_tree/engine.rb: -------------------------------------------------------------------------------- 1 | require "activeadmin" 2 | 3 | module ActiveAdmin 4 | module SortableTree 5 | class Engine < ::Rails::Engine 6 | engine_name "active_admin-sortable_tree" 7 | 8 | config.aa_sortable_tree = ActiveSupport::OrderedOptions.new 9 | config.aa_sortable_tree.register_assets = true 10 | 11 | initializer "active_admin-sortable_tree.precompile", group: :all do |app| 12 | app.config.assets.precompile += [ 13 | "active_admin/sortable.css", 14 | "active_admin/sortable.js" 15 | ] 16 | end 17 | 18 | initializer "active_admin-sortable_tree.register_assets" do 19 | if config.aa_sortable_tree.register_assets 20 | ActiveAdmin.application.register_stylesheet "active_admin/sortable.css" 21 | ActiveAdmin.application.register_javascript "active_admin/sortable.js" 22 | end 23 | end 24 | end 25 | end 26 | end 27 | -------------------------------------------------------------------------------- /lib/active_admin/sortable_tree/version.rb: -------------------------------------------------------------------------------- 1 | module ActiveAdmin 2 | module SortableTree 3 | VERSION = "2.1.0" 4 | end 5 | end 6 | -------------------------------------------------------------------------------- /lib/active_admin/views/index_as_block_decorator.rb: -------------------------------------------------------------------------------- 1 | module ActiveAdmin 2 | module Views 3 | IndexAsBlock.class_eval do 4 | 5 | def build(page_presenter, collection) 6 | add_class "index" 7 | if active_admin_config.dsl.sortable_options 8 | set_attribute "data-sortable-type", "plain" 9 | 10 | sort_url = if (( sort_url_block = active_admin_config.dsl.sortable_options[:sort_url] )) 11 | sort_url_block.call(self) 12 | else 13 | url_for(:action => :sort) 14 | end 15 | 16 | set_attribute "data-sortable-url", sort_url 17 | collection = collection.sort_by do |a| 18 | a.send(active_admin_config.dsl.sortable_options[:sorting_attribute]) || 1 19 | end 20 | end 21 | resource_selection_toggle_panel if active_admin_config.batch_actions.any? 22 | collection.each do |obj| 23 | instance_exec(obj, &page_presenter.block) 24 | end 25 | end 26 | 27 | end 28 | end 29 | end 30 | 31 | -------------------------------------------------------------------------------- /lib/active_admin/views/index_as_sortable.rb: -------------------------------------------------------------------------------- 1 | module ActiveAdmin 2 | module Views 3 | 4 | # = Index as a Sortable List or Tree 5 | class IndexAsSortable < ActiveAdmin::Component 6 | def build(page_presenter, collection) 7 | @page_presenter = page_presenter 8 | @collection = if tree? 9 | roots 10 | else 11 | collection 12 | end 13 | @collection = @collection.sort_by do |a| 14 | a.send(options[:sorting_attribute]) || 1 15 | end 16 | 17 | @resource_name = ActiveAdmin::SortableTree::Compatibility.normalized_resource_name(active_admin_config.resource_name) 18 | 19 | # Call the block passed in. This will set the 20 | # title and body methods 21 | instance_eval &page_presenter.block if page_presenter.block 22 | 23 | add_class "index" 24 | build_list 25 | end 26 | 27 | def self.index_name; "sortable"; end 28 | 29 | def options 30 | active_admin_config.dsl.sortable_options 31 | end 32 | 33 | def roots 34 | roots_collection || default_roots_collection 35 | end 36 | 37 | # Find the roots by calling the roots method directly on the resource. 38 | # This effectively performs: 39 | # 40 | # TreeNode.roots # => [#, ... ] 41 | # 42 | # Returns collection of roots. 43 | def default_roots_collection 44 | resource_class.send(options[:roots_method]) 45 | end 46 | 47 | # Use user-defined logic to find the root nodes. This executes a callable 48 | # object within the context of the resource's controller. 49 | # 50 | # Example 51 | # 52 | # options[:roots_collection] = proc { current_user.tree_nodes.roots } 53 | # 54 | # Returns collection of roots. 55 | def roots_collection 56 | if (callable = options[:roots_collection]) 57 | controller.instance_exec(&callable) 58 | end 59 | end 60 | 61 | def tree? 62 | !!options[:tree] 63 | end 64 | 65 | # Setter method for the configuration of the label 66 | def label(method = nil, &block) 67 | if block_given? || method 68 | @label = block_given? ? block : method 69 | end 70 | @label 71 | end 72 | 73 | # Adds links to View, Edit and Delete 74 | def actions(options = {}, &block) 75 | options = { :defaults => true }.merge(options) 76 | @default_actions = options[:defaults] 77 | @other_actions = block 78 | end 79 | 80 | protected 81 | 82 | def build_list 83 | resource_selection_toggle_panel if active_admin_config.batch_actions.any? 84 | 85 | ol sortable_data_options do 86 | @collection.each do |item| 87 | build_nested_item(item) 88 | end 89 | end 90 | end 91 | 92 | def sortable_data_options 93 | return {} if !sortable? 94 | 95 | sort_url = if (( sort_url_block = options[:sort_url] )) 96 | sort_url_block.call(self) 97 | else 98 | url_for(:action => :sort) 99 | end 100 | { 101 | "data-sortable-type" => tree? ? "tree" : "list", 102 | "data-sortable-url" => sort_url, 103 | "data-max-levels" => options[:max_levels], 104 | "data-start-collapsed" => options[:start_collapsed], 105 | "data-protect-root" => options[:protect_root], 106 | } 107 | end 108 | 109 | def sortable? 110 | if (sortable = options[:sortable]).respond_to? :call 111 | controller.instance_exec(&sortable) 112 | else 113 | sortable 114 | end 115 | end 116 | 117 | def build_nested_item(item) 118 | li :id => "#{@resource_name}_#{item.id}" do 119 | 120 | div :class => "item " << cycle("odd", "even", :name => "list_class") do 121 | if active_admin_config.batch_actions.any? 122 | div :class => "cell left" do 123 | resource_selection_cell(item) 124 | end 125 | end 126 | 127 | if options[:collapsible] && item.send(options[:children_method]).any? 128 | span :class => :disclose do 129 | span 130 | end 131 | end 132 | 133 | h3 :class => "cell left" do 134 | call_method_or_proc_on(item, @label) 135 | end 136 | div :class => "cell right" do 137 | build_actions(item) 138 | end 139 | end 140 | 141 | ol do 142 | item.send(options[:children_method]).order(options[:sorting_attribute]).each do |c| 143 | build_nested_item(c) 144 | end 145 | end if tree? 146 | end 147 | end 148 | 149 | def build_actions(resource) 150 | links = ''.html_safe 151 | if @default_actions 152 | if controller.action_methods.include?('show') && authorized?(ActiveAdmin::Auth::READ, resource) 153 | links << link_to(I18n.t('active_admin.view'), resource_path(resource), :class => "member_link view_link") 154 | end 155 | if controller.action_methods.include?('edit') && authorized?(ActiveAdmin::Auth::UPDATE, resource) 156 | links << link_to(I18n.t('active_admin.edit'), edit_resource_path(resource), :class => "member_link edit_link") 157 | end 158 | if controller.action_methods.include?('destroy') && authorized?(ActiveAdmin::Auth::DESTROY, resource) 159 | links << link_to(I18n.t('active_admin.delete'), resource_path(resource), :method => :delete, :data => {:confirm => I18n.t('active_admin.delete_confirmation')}, :class => "member_link delete_link") 160 | end 161 | end 162 | links << instance_exec(resource, &@other_actions) if @other_actions 163 | links 164 | end 165 | 166 | end 167 | end 168 | end 169 | 170 | -------------------------------------------------------------------------------- /lib/activeadmin-sortable-tree.rb: -------------------------------------------------------------------------------- 1 | require 'active_admin/sortable' 2 | -------------------------------------------------------------------------------- /script/rails: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env ruby 2 | 3 | ENGINE_ROOT = File.expand_path('../..', __FILE__) 4 | ENGINE_PATH = File.expand_path('../../lib/active_admin/sortable_tree/engine', __FILE__) 5 | 6 | # Set up gems listed in the Gemfile. 7 | ENV['BUNDLE_GEMFILE'] ||= File.expand_path('../../Gemfile', __FILE__) 8 | require 'bundler/setup' if File.exist?(ENV['BUNDLE_GEMFILE']) 9 | 10 | require 'rails/all' 11 | require 'rails/engine/commands' 12 | -------------------------------------------------------------------------------- /spec/dummy/README.rdoc: -------------------------------------------------------------------------------- 1 | == Welcome to Rails 2 | 3 | Rails is a web-application framework that includes everything needed to create 4 | database-backed web applications according to the Model-View-Control pattern. 5 | 6 | This pattern splits the view (also called the presentation) into "dumb" 7 | templates that are primarily responsible for inserting pre-built data in between 8 | HTML tags. The model contains the "smart" domain objects (such as Account, 9 | Product, Person, Post) that holds all the business logic and knows how to 10 | persist themselves to a database. The controller handles the incoming requests 11 | (such as Save New Account, Update Product, Show Post) by manipulating the model 12 | and directing data to the view. 13 | 14 | In Rails, the model is handled by what's called an object-relational mapping 15 | layer entitled Active Record. This layer allows you to present the data from 16 | database rows as objects and embellish these data objects with business logic 17 | methods. You can read more about Active Record in 18 | link:files/vendor/rails/activerecord/README.html. 19 | 20 | The controller and view are handled by the Action Pack, which handles both 21 | layers by its two parts: Action View and Action Controller. These two layers 22 | are bundled in a single package due to their heavy interdependence. This is 23 | unlike the relationship between the Active Record and Action Pack that is much 24 | more separate. Each of these packages can be used independently outside of 25 | Rails. You can read more about Action Pack in 26 | link:files/vendor/rails/actionpack/README.html. 27 | 28 | 29 | == Getting Started 30 | 31 | 1. At the command prompt, create a new Rails application: 32 | rails new myapp (where myapp is the application name) 33 | 34 | 2. Change directory to myapp and start the web server: 35 | cd myapp; rails server (run with --help for options) 36 | 37 | 3. Go to http://localhost:3000/ and you'll see: 38 | "Welcome aboard: You're riding Ruby on Rails!" 39 | 40 | 4. Follow the guidelines to start developing your application. You can find 41 | the following resources handy: 42 | 43 | * The Getting Started Guide: http://guides.rubyonrails.org/getting_started.html 44 | * Ruby on Rails Tutorial Book: http://www.railstutorial.org/ 45 | 46 | 47 | == Debugging Rails 48 | 49 | Sometimes your application goes wrong. Fortunately there are a lot of tools that 50 | will help you debug it and get it back on the rails. 51 | 52 | First area to check is the application log files. Have "tail -f" commands 53 | running on the server.log and development.log. Rails will automatically display 54 | debugging and runtime information to these files. Debugging info will also be 55 | shown in the browser on requests from 127.0.0.1. 56 | 57 | You can also log your own messages directly into the log file from your code 58 | using the Ruby logger class from inside your controllers. Example: 59 | 60 | class WeblogController < ActionController::Base 61 | def destroy 62 | @weblog = Weblog.find(params[:id]) 63 | @weblog.destroy 64 | logger.info("#{Time.now} Destroyed Weblog ID ##{@weblog.id}!") 65 | end 66 | end 67 | 68 | The result will be a message in your log file along the lines of: 69 | 70 | Mon Oct 08 14:22:29 +1000 2007 Destroyed Weblog ID #1! 71 | 72 | More information on how to use the logger is at http://www.ruby-doc.org/core/ 73 | 74 | Also, Ruby documentation can be found at http://www.ruby-lang.org/. There are 75 | several books available online as well: 76 | 77 | * Programming Ruby: http://www.ruby-doc.org/docs/ProgrammingRuby/ (Pickaxe) 78 | * Learn to Program: http://pine.fm/LearnToProgram/ (a beginners guide) 79 | 80 | These two books will bring you up to speed on the Ruby language and also on 81 | programming in general. 82 | 83 | 84 | == Debugger 85 | 86 | Debugger support is available through the debugger command when you start your 87 | Mongrel or WEBrick server with --debugger. This means that you can break out of 88 | execution at any point in the code, investigate and change the model, and then, 89 | resume execution! You need to install ruby-debug to run the server in debugging 90 | mode. With gems, use sudo gem install ruby-debug. Example: 91 | 92 | class WeblogController < ActionController::Base 93 | def index 94 | @posts = Post.all 95 | debugger 96 | end 97 | end 98 | 99 | So the controller will accept the action, run the first line, then present you 100 | with a IRB prompt in the server window. Here you can do things like: 101 | 102 | >> @posts.inspect 103 | => "[#nil, "body"=>nil, "id"=>"1"}>, 105 | #"Rails", "body"=>"Only ten..", "id"=>"2"}>]" 107 | >> @posts.first.title = "hello from a debugger" 108 | => "hello from a debugger" 109 | 110 | ...and even better, you can examine how your runtime objects actually work: 111 | 112 | >> f = @posts.first 113 | => #nil, "body"=>nil, "id"=>"1"}> 114 | >> f. 115 | Display all 152 possibilities? (y or n) 116 | 117 | Finally, when you're ready to resume execution, you can enter "cont". 118 | 119 | 120 | == Console 121 | 122 | The console is a Ruby shell, which allows you to interact with your 123 | application's domain model. Here you'll have all parts of the application 124 | configured, just like it is when the application is running. You can inspect 125 | domain models, change values, and save to the database. Starting the script 126 | without arguments will launch it in the development environment. 127 | 128 | To start the console, run rails console from the application 129 | directory. 130 | 131 | Options: 132 | 133 | * Passing the -s, --sandbox argument will rollback any modifications 134 | made to the database. 135 | * Passing an environment name as an argument will load the corresponding 136 | environment. Example: rails console production. 137 | 138 | To reload your controllers and models after launching the console run 139 | reload! 140 | 141 | More information about irb can be found at: 142 | link:http://www.rubycentral.org/pickaxe/irb.html 143 | 144 | 145 | == dbconsole 146 | 147 | You can go to the command line of your database directly through rails 148 | dbconsole. You would be connected to the database with the credentials 149 | defined in database.yml. Starting the script without arguments will connect you 150 | to the development database. Passing an argument will connect you to a different 151 | database, like rails dbconsole production. Currently works for MySQL, 152 | PostgreSQL and SQLite 3. 153 | 154 | == Description of Contents 155 | 156 | The default directory structure of a generated Ruby on Rails application: 157 | 158 | |-- app 159 | | |-- assets 160 | | | |-- images 161 | | | |-- javascripts 162 | | | `-- stylesheets 163 | | |-- controllers 164 | | |-- helpers 165 | | |-- mailers 166 | | |-- models 167 | | `-- views 168 | | `-- layouts 169 | |-- config 170 | | |-- environments 171 | | |-- initializers 172 | | `-- locales 173 | |-- db 174 | |-- doc 175 | |-- lib 176 | | |-- assets 177 | | `-- tasks 178 | |-- log 179 | |-- public 180 | |-- script 181 | |-- test 182 | | |-- fixtures 183 | | |-- functional 184 | | |-- integration 185 | | |-- performance 186 | | `-- unit 187 | |-- tmp 188 | | `-- cache 189 | | `-- assets 190 | `-- vendor 191 | |-- assets 192 | | |-- javascripts 193 | | `-- stylesheets 194 | `-- plugins 195 | 196 | app 197 | Holds all the code that's specific to this particular application. 198 | 199 | app/assets 200 | Contains subdirectories for images, stylesheets, and JavaScript files. 201 | 202 | app/controllers 203 | Holds controllers that should be named like weblogs_controller.rb for 204 | automated URL mapping. All controllers should descend from 205 | ApplicationController which itself descends from ActionController::Base. 206 | 207 | app/models 208 | Holds models that should be named like post.rb. Models descend from 209 | ActiveRecord::Base by default. 210 | 211 | app/views 212 | Holds the template files for the view that should be named like 213 | weblogs/index.html.erb for the WeblogsController#index action. All views use 214 | eRuby syntax by default. 215 | 216 | app/views/layouts 217 | Holds the template files for layouts to be used with views. This models the 218 | common header/footer method of wrapping views. In your views, define a layout 219 | using the layout :default and create a file named default.html.erb. 220 | Inside default.html.erb, call <% yield %> to render the view using this 221 | layout. 222 | 223 | app/helpers 224 | Holds view helpers that should be named like weblogs_helper.rb. These are 225 | generated for you automatically when using generators for controllers. 226 | Helpers can be used to wrap functionality for your views into methods. 227 | 228 | config 229 | Configuration files for the Rails environment, the routing map, the database, 230 | and other dependencies. 231 | 232 | db 233 | Contains the database schema in schema.rb. db/migrate contains all the 234 | sequence of Migrations for your schema. 235 | 236 | doc 237 | This directory is where your application documentation will be stored when 238 | generated using rake doc:app 239 | 240 | lib 241 | Application specific libraries. Basically, any kind of custom code that 242 | doesn't belong under controllers, models, or helpers. This directory is in 243 | the load path. 244 | 245 | public 246 | The directory available for the web server. Also contains the dispatchers and the 247 | default HTML files. This should be set as the DOCUMENT_ROOT of your web 248 | server. 249 | 250 | script 251 | Helper scripts for automation and generation. 252 | 253 | test 254 | Unit and functional tests along with fixtures. When using the rails generate 255 | command, template test files will be generated for you and placed in this 256 | directory. 257 | 258 | vendor 259 | External libraries that the application depends on. Also includes the plugins 260 | subdirectory. If the app has frozen rails, those gems also go here, under 261 | vendor/rails/. This directory is in the load path. 262 | -------------------------------------------------------------------------------- /spec/dummy/Rakefile: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env rake 2 | # Add your own tasks in files placed in lib/tasks ending in .rake, 3 | # for example lib/tasks/capistrano.rake, and they will automatically be available to Rake. 4 | 5 | require File.expand_path('../config/application', __FILE__) 6 | 7 | Dummy::Application.load_tasks 8 | -------------------------------------------------------------------------------- /spec/dummy/app/admin/category.rb: -------------------------------------------------------------------------------- 1 | ActiveAdmin.register Category do 2 | sortable 3 | 4 | permit_params :name, :ancestry, :description, :position if Float(ENV['RAILS_VERSION']) >= 4.0 5 | 6 | index as: :sortable do 7 | label :name 8 | actions 9 | end 10 | 11 | form do |f| 12 | f.inputs :name, :description 13 | f.actions 14 | end 15 | end 16 | -------------------------------------------------------------------------------- /spec/dummy/app/admin/category_sort_disabled.rb: -------------------------------------------------------------------------------- 1 | ActiveAdmin.register Category, as: "CategoryDisabledSort" do 2 | sortable sortable: false 3 | 4 | permit_params :name, :ancestry, :description, :position if Float(ENV['RAILS_VERSION']) >= 4.0 5 | 6 | index as: :sortable do 7 | label :name 8 | actions 9 | end 10 | 11 | form do |f| 12 | f.inputs :name, :description 13 | f.actions 14 | end 15 | end 16 | -------------------------------------------------------------------------------- /spec/dummy/app/admin/category_tree.rb: -------------------------------------------------------------------------------- 1 | ActiveAdmin.register Category, as: "CategoryTree" do 2 | sortable tree: true 3 | actions :index 4 | 5 | index as: :sortable do 6 | label :name 7 | actions 8 | end 9 | end 10 | -------------------------------------------------------------------------------- /spec/dummy/app/admin/dashboard.rb: -------------------------------------------------------------------------------- 1 | ActiveAdmin.register_page "Dashboard" do 2 | content do 3 | 4 | end 5 | end 6 | -------------------------------------------------------------------------------- /spec/dummy/app/assets/javascripts/active_admin.js: -------------------------------------------------------------------------------- 1 | //= require active_admin/base 2 | //= require active_admin/sortable 3 | //= require jquery.simulate 4 | -------------------------------------------------------------------------------- /spec/dummy/app/assets/javascripts/application.js: -------------------------------------------------------------------------------- 1 | // This is a manifest file that'll be compiled into application.js, which will include all the files 2 | // listed below. 3 | // 4 | // Any JavaScript/Coffee file within this directory, lib/assets/javascripts, vendor/assets/javascripts, 5 | // or vendor/assets/javascripts of plugins, if any, can be referenced here using a relative path. 6 | // 7 | // It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the 8 | // the compiled file. 9 | // 10 | // WARNING: THE FIRST BLANK LINE MARKS THE END OF WHAT'S TO BE PROCESSED, ANY BLANK LINE SHOULD 11 | // GO AFTER THE REQUIRES BELOW. 12 | // 13 | //= require jquery 14 | //= require jquery_ujs 15 | //= require_tree . 16 | -------------------------------------------------------------------------------- /spec/dummy/app/assets/javascripts/jquery.simulate.js: -------------------------------------------------------------------------------- 1 | /*! 2 | * jQuery Simulate v@VERSION - simulate browser mouse and keyboard events 3 | * https://github.com/jquery/jquery-simulate 4 | * 5 | * Copyright 2012 jQuery Foundation and other contributors 6 | * Released under the MIT license. 7 | * http://jquery.org/license 8 | * 9 | * Date: @DATE 10 | */ 11 | 12 | ;(function( $, undefined ) { 13 | 14 | var rkeyEvent = /^key/, 15 | rmouseEvent = /^(?:mouse|contextmenu)|click/; 16 | 17 | $.fn.simulate = function( type, options ) { 18 | return this.each(function() { 19 | new $.simulate( this, type, options ); 20 | }); 21 | }; 22 | 23 | $.simulate = function( elem, type, options ) { 24 | var method = $.camelCase( "simulate-" + type ); 25 | 26 | this.target = elem; 27 | this.options = options; 28 | 29 | if ( this[ method ] ) { 30 | this[ method ](); 31 | } else { 32 | this.simulateEvent( elem, type, options ); 33 | } 34 | }; 35 | 36 | $.extend( $.simulate, { 37 | 38 | keyCode: { 39 | BACKSPACE: 8, 40 | COMMA: 188, 41 | DELETE: 46, 42 | DOWN: 40, 43 | END: 35, 44 | ENTER: 13, 45 | ESCAPE: 27, 46 | HOME: 36, 47 | LEFT: 37, 48 | NUMPAD_ADD: 107, 49 | NUMPAD_DECIMAL: 110, 50 | NUMPAD_DIVIDE: 111, 51 | NUMPAD_ENTER: 108, 52 | NUMPAD_MULTIPLY: 106, 53 | NUMPAD_SUBTRACT: 109, 54 | PAGE_DOWN: 34, 55 | PAGE_UP: 33, 56 | PERIOD: 190, 57 | RIGHT: 39, 58 | SPACE: 32, 59 | TAB: 9, 60 | UP: 38 61 | }, 62 | 63 | buttonCode: { 64 | LEFT: 0, 65 | MIDDLE: 1, 66 | RIGHT: 2 67 | } 68 | }); 69 | 70 | $.extend( $.simulate.prototype, { 71 | 72 | simulateEvent: function( elem, type, options ) { 73 | var event = this.createEvent( type, options ); 74 | this.dispatchEvent( elem, type, event, options ); 75 | }, 76 | 77 | createEvent: function( type, options ) { 78 | if ( rkeyEvent.test( type ) ) { 79 | return this.keyEvent( type, options ); 80 | } 81 | 82 | if ( rmouseEvent.test( type ) ) { 83 | return this.mouseEvent( type, options ); 84 | } 85 | }, 86 | 87 | mouseEvent: function( type, options ) { 88 | var event, eventDoc, doc, body; 89 | options = $.extend({ 90 | bubbles: true, 91 | cancelable: (type !== "mousemove"), 92 | view: window, 93 | detail: 0, 94 | screenX: 0, 95 | screenY: 0, 96 | clientX: 1, 97 | clientY: 1, 98 | ctrlKey: false, 99 | altKey: false, 100 | shiftKey: false, 101 | metaKey: false, 102 | button: 0, 103 | relatedTarget: undefined 104 | }, options ); 105 | 106 | if ( document.createEvent ) { 107 | event = document.createEvent( "MouseEvents" ); 108 | event.initMouseEvent( type, options.bubbles, options.cancelable, 109 | options.view, options.detail, 110 | options.screenX, options.screenY, options.clientX, options.clientY, 111 | options.ctrlKey, options.altKey, options.shiftKey, options.metaKey, 112 | options.button, options.relatedTarget || document.body.parentNode ); 113 | 114 | // IE 9+ creates events with pageX and pageY set to 0. 115 | // Trying to modify the properties throws an error, 116 | // so we define getters to return the correct values. 117 | if ( event.pageX === 0 && event.pageY === 0 && Object.defineProperty ) { 118 | eventDoc = event.relatedTarget.ownerDocument || document; 119 | doc = eventDoc.documentElement; 120 | body = eventDoc.body; 121 | 122 | Object.defineProperty( event, "pageX", { 123 | get: function() { 124 | return options.clientX + 125 | ( doc && doc.scrollLeft || body && body.scrollLeft || 0 ) - 126 | ( doc && doc.clientLeft || body && body.clientLeft || 0 ); 127 | } 128 | }); 129 | Object.defineProperty( event, "pageY", { 130 | get: function() { 131 | return options.clientY + 132 | ( doc && doc.scrollTop || body && body.scrollTop || 0 ) - 133 | ( doc && doc.clientTop || body && body.clientTop || 0 ); 134 | } 135 | }); 136 | } 137 | } else if ( document.createEventObject ) { 138 | event = document.createEventObject(); 139 | $.extend( event, options ); 140 | // standards event.button uses constants defined here: http://msdn.microsoft.com/en-us/library/ie/ff974877(v=vs.85).aspx 141 | // old IE event.button uses constants defined here: http://msdn.microsoft.com/en-us/library/ie/ms533544(v=vs.85).aspx 142 | // so we actually need to map the standard back to oldIE 143 | event.button = { 144 | 0: 1, 145 | 1: 4, 146 | 2: 2 147 | }[ event.button ] || event.button; 148 | } 149 | 150 | return event; 151 | }, 152 | 153 | keyEvent: function( type, options ) { 154 | var event; 155 | options = $.extend({ 156 | bubbles: true, 157 | cancelable: true, 158 | view: window, 159 | ctrlKey: false, 160 | altKey: false, 161 | shiftKey: false, 162 | metaKey: false, 163 | keyCode: 0, 164 | charCode: undefined 165 | }, options ); 166 | 167 | if ( document.createEvent ) { 168 | try { 169 | event = document.createEvent( "KeyEvents" ); 170 | event.initKeyEvent( type, options.bubbles, options.cancelable, options.view, 171 | options.ctrlKey, options.altKey, options.shiftKey, options.metaKey, 172 | options.keyCode, options.charCode ); 173 | // initKeyEvent throws an exception in WebKit 174 | // see: http://stackoverflow.com/questions/6406784/initkeyevent-keypress-only-works-in-firefox-need-a-cross-browser-solution 175 | // and also https://bugs.webkit.org/show_bug.cgi?id=13368 176 | // fall back to a generic event until we decide to implement initKeyboardEvent 177 | } catch( err ) { 178 | event = document.createEvent( "Events" ); 179 | event.initEvent( type, options.bubbles, options.cancelable ); 180 | $.extend( event, { 181 | view: options.view, 182 | ctrlKey: options.ctrlKey, 183 | altKey: options.altKey, 184 | shiftKey: options.shiftKey, 185 | metaKey: options.metaKey, 186 | keyCode: options.keyCode, 187 | charCode: options.charCode 188 | }); 189 | } 190 | } else if ( document.createEventObject ) { 191 | event = document.createEventObject(); 192 | $.extend( event, options ); 193 | } 194 | 195 | if ( !!/msie [\w.]+/.exec( navigator.userAgent.toLowerCase() ) || (({}).toString.call( window.opera ) === "[object Opera]") ) { 196 | event.keyCode = (options.charCode > 0) ? options.charCode : options.keyCode; 197 | event.charCode = undefined; 198 | } 199 | 200 | return event; 201 | }, 202 | 203 | dispatchEvent: function( elem, type, event ) { 204 | if ( elem[ type ] ) { 205 | elem[ type ](); 206 | } else if ( elem.dispatchEvent ) { 207 | elem.dispatchEvent( event ); 208 | } else if ( elem.fireEvent ) { 209 | elem.fireEvent( "on" + type, event ); 210 | } 211 | }, 212 | 213 | simulateFocus: function() { 214 | var focusinEvent, 215 | triggered = false, 216 | element = $( this.target ); 217 | 218 | function trigger() { 219 | triggered = true; 220 | } 221 | 222 | element.bind( "focus", trigger ); 223 | element[ 0 ].focus(); 224 | 225 | if ( !triggered ) { 226 | focusinEvent = $.Event( "focusin" ); 227 | focusinEvent.preventDefault(); 228 | element.trigger( focusinEvent ); 229 | element.triggerHandler( "focus" ); 230 | } 231 | element.unbind( "focus", trigger ); 232 | }, 233 | 234 | simulateBlur: function() { 235 | var focusoutEvent, 236 | triggered = false, 237 | element = $( this.target ); 238 | 239 | function trigger() { 240 | triggered = true; 241 | } 242 | 243 | element.bind( "blur", trigger ); 244 | element[ 0 ].blur(); 245 | 246 | // blur events are async in IE 247 | setTimeout(function() { 248 | // IE won't let the blur occur if the window is inactive 249 | if ( element[ 0 ].ownerDocument.activeElement === element[ 0 ] ) { 250 | element[ 0 ].ownerDocument.body.focus(); 251 | } 252 | 253 | // Firefox won't trigger events if the window is inactive 254 | // IE doesn't trigger events if we had to manually focus the body 255 | if ( !triggered ) { 256 | focusoutEvent = $.Event( "focusout" ); 257 | focusoutEvent.preventDefault(); 258 | element.trigger( focusoutEvent ); 259 | element.triggerHandler( "blur" ); 260 | } 261 | element.unbind( "blur", trigger ); 262 | }, 1 ); 263 | } 264 | }); 265 | 266 | 267 | 268 | /** complex events **/ 269 | 270 | function findCenter( elem ) { 271 | var offset, 272 | document = $( elem.ownerDocument ); 273 | elem = $( elem ); 274 | offset = elem.offset(); 275 | 276 | return { 277 | x: offset.left + elem.outerWidth() / 2 - document.scrollLeft(), 278 | y: offset.top + elem.outerHeight() / 2 - document.scrollTop() 279 | }; 280 | } 281 | 282 | $.extend( $.simulate.prototype, { 283 | simulateDrag: function() { 284 | var i = 0, 285 | target = this.target, 286 | options = this.options, 287 | center = findCenter( target ), 288 | x = Math.floor( center.x ), 289 | y = Math.floor( center.y ), 290 | dx = options.dx || 0, 291 | dy = options.dy || 0, 292 | moves = options.moves || 3, 293 | coord = { clientX: x, clientY: y }; 294 | 295 | this.simulateEvent( target, "mousedown", coord ); 296 | 297 | for ( ; i < moves ; i++ ) { 298 | x += dx / moves; 299 | y += dy / moves; 300 | 301 | coord = { 302 | clientX: Math.round( x ), 303 | clientY: Math.round( y ) 304 | }; 305 | 306 | this.simulateEvent( document, "mousemove", coord ); 307 | } 308 | 309 | this.simulateEvent( target, "mouseup", coord ); 310 | this.simulateEvent( target, "click", coord ); 311 | } 312 | }); 313 | 314 | })( jQuery ); 315 | -------------------------------------------------------------------------------- /spec/dummy/app/assets/stylesheets/active_admin.css.scss: -------------------------------------------------------------------------------- 1 | // SASS variable overrides must be declared before loading up Active Admin's styles. 2 | // 3 | // To view the variables that Active Admin provides, take a look at 4 | // `app/assets/stylesheets/active_admin/mixins/_variables.css.scss` in the 5 | // Active Admin source. 6 | // 7 | // For example, to change the sidebar width: 8 | // $sidebar-width: 242px; 9 | 10 | // Active Admin's got SASS! 11 | @import "active_admin/mixins"; 12 | @import "active_admin/base"; 13 | @import "active_admin/sortable"; 14 | 15 | // Overriding any non-variable SASS must be done after the fact. 16 | // For example, to change the default status-tag color: 17 | // 18 | // .status_tag { background: #6090DB; } 19 | -------------------------------------------------------------------------------- /spec/dummy/app/assets/stylesheets/application.css: -------------------------------------------------------------------------------- 1 | /* 2 | * This is a manifest file that'll be compiled into application.css, which will include all the files 3 | * listed below. 4 | * 5 | * Any CSS and SCSS file within this directory, lib/assets/stylesheets, vendor/assets/stylesheets, 6 | * or vendor/assets/stylesheets of plugins, if any, can be referenced here using a relative path. 7 | * 8 | * You're free to add application-wide styles to this file and they'll appear at the top of the 9 | * compiled file, but it's generally better to create a new file per style scope. 10 | * 11 | *= require_self 12 | *= require_tree . 13 | */ 14 | -------------------------------------------------------------------------------- /spec/dummy/app/controllers/application_controller.rb: -------------------------------------------------------------------------------- 1 | class ApplicationController < ActionController::Base 2 | protect_from_forgery 3 | end 4 | -------------------------------------------------------------------------------- /spec/dummy/app/helpers/application_helper.rb: -------------------------------------------------------------------------------- 1 | module ApplicationHelper 2 | end 3 | -------------------------------------------------------------------------------- /spec/dummy/app/mailers/.gitkeep: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/zorab47/active_admin-sortable_tree/7f2b0fb7f407a526265182303da67a4457c05c31/spec/dummy/app/mailers/.gitkeep -------------------------------------------------------------------------------- /spec/dummy/app/models/.gitkeep: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/zorab47/active_admin-sortable_tree/7f2b0fb7f407a526265182303da67a4457c05c31/spec/dummy/app/models/.gitkeep -------------------------------------------------------------------------------- /spec/dummy/app/models/admin_user.rb: -------------------------------------------------------------------------------- 1 | class AdminUser < ActiveRecord::Base 2 | # Include default devise modules. Others available are: 3 | # :confirmable, :lockable, :timeoutable and :omniauthable 4 | devise :database_authenticatable, 5 | :recoverable, :rememberable, :trackable, :validatable 6 | end 7 | -------------------------------------------------------------------------------- /spec/dummy/app/models/category.rb: -------------------------------------------------------------------------------- 1 | class Category < ActiveRecord::Base 2 | has_ancestry 3 | attr_accessible :ancestry, :description, :name, :position if Float(ENV['RAILS_VERSION']) < 4 4 | end 5 | -------------------------------------------------------------------------------- /spec/dummy/app/views/layouts/application.html.erb: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | Dummy 5 | <%= stylesheet_link_tag "application", :media => "all" %> 6 | <%= javascript_include_tag "application" %> 7 | <%= csrf_meta_tags %> 8 | 9 | 10 | 11 | <%= yield %> 12 | 13 | 14 | 15 | -------------------------------------------------------------------------------- /spec/dummy/config.ru: -------------------------------------------------------------------------------- 1 | # This file is used by Rack-based servers to start the application. 2 | 3 | require ::File.expand_path('../config/environment', __FILE__) 4 | run Dummy::Application 5 | -------------------------------------------------------------------------------- /spec/dummy/config/application.rb: -------------------------------------------------------------------------------- 1 | require File.expand_path('../boot', __FILE__) 2 | 3 | require "rails/all" 4 | 5 | Bundler.require(*Rails.groups) 6 | 7 | require "active_admin/sortable_tree" 8 | 9 | module Dummy 10 | class Application < Rails::Application 11 | # Settings in config/environments/* take precedence over those specified here. 12 | # Application configuration should go into files in config/initializers 13 | # -- all .rb files in that directory are automatically loaded. 14 | 15 | # Custom directories with classes and modules you want to be autoloadable. 16 | config.autoload_paths += %W(#{config.root}/app/models) 17 | 18 | # Only load the plugins named here, in the order given (default is alphabetical). 19 | # :all can be used as a placeholder for all plugins not explicitly named. 20 | # config.plugins = [ :exception_notification, :ssl_requirement, :all ] 21 | 22 | # Activate observers that should always be running. 23 | # config.active_record.observers = :cacher, :garbage_collector, :forum_observer 24 | 25 | # Set Time.zone default to the specified zone and make Active Record auto-convert to this zone. 26 | # Run "rake -D time" for a list of tasks for finding time zone names. Default is UTC. 27 | # config.time_zone = 'Central Time (US & Canada)' 28 | 29 | # The default locale is :en and all translations from config/locales/*.rb,yml are auto loaded. 30 | # config.i18n.load_path += Dir[Rails.root.join('my', 'locales', '*.{rb,yml}').to_s] 31 | # config.i18n.default_locale = :de 32 | I18n.enforce_available_locales = false 33 | 34 | # Configure the default encoding used in templates for Ruby 1.9. 35 | config.encoding = "utf-8" 36 | 37 | # Configure sensitive parameters which will be filtered from the log file. 38 | config.filter_parameters += [:password] 39 | 40 | # Enable escaping HTML in JSON. 41 | config.active_support.escape_html_entities_in_json = true 42 | 43 | # Use SQL instead of Active Record's schema dumper when creating the database. 44 | # This is necessary if your schema can't be completely dumped by the schema dumper, 45 | # like if you have constraints or database-specific column types 46 | # config.active_record.schema_format = :sql 47 | 48 | # Enable the asset pipeline 49 | config.assets.enabled = true 50 | 51 | # Version of your assets, change this if you want to expire all your assets 52 | config.assets.version = '1.0' 53 | 54 | config.aa_sortable_tree.register_assets = false 55 | end 56 | end 57 | 58 | ActiveRecord::Migration.verbose = false 59 | -------------------------------------------------------------------------------- /spec/dummy/config/boot.rb: -------------------------------------------------------------------------------- 1 | require 'rubygems' 2 | gemfile = File.expand_path('../../../../Gemfile', __FILE__) 3 | 4 | if File.exist?(gemfile) 5 | ENV['BUNDLE_GEMFILE'] = gemfile 6 | require 'bundler' 7 | Bundler.setup 8 | end 9 | 10 | $:.unshift File.expand_path('../../../../lib', __FILE__) -------------------------------------------------------------------------------- /spec/dummy/config/database.yml: -------------------------------------------------------------------------------- 1 | # SQLite version 3.x 2 | # gem install sqlite3 3 | # 4 | # Ensure the SQLite 3 gem is defined in your Gemfile 5 | # gem 'sqlite3' 6 | development: 7 | adapter: sqlite3 8 | database: db/development.sqlite3 9 | pool: 5 10 | timeout: 5000 11 | 12 | # Warning: The database defined as "test" will be erased and 13 | # re-generated from your development database when you run "rake". 14 | # Do not set this db to the same as development or production. 15 | test: 16 | adapter: sqlite3 17 | database: db/test.sqlite3 18 | pool: 5 19 | timeout: 5000 20 | 21 | production: 22 | adapter: sqlite3 23 | database: db/production.sqlite3 24 | pool: 5 25 | timeout: 5000 26 | -------------------------------------------------------------------------------- /spec/dummy/config/environment.rb: -------------------------------------------------------------------------------- 1 | # Load the rails application 2 | require File.expand_path('../application', __FILE__) 3 | 4 | # Initialize the rails application 5 | Dummy::Application.initialize! 6 | -------------------------------------------------------------------------------- /spec/dummy/config/environments/development.rb: -------------------------------------------------------------------------------- 1 | Dummy::Application.configure do 2 | # Settings specified here will take precedence over those in config/application.rb 3 | config.eager_load = false 4 | 5 | # In the development environment your application's code is reloaded on 6 | # every request. This slows down response time but is perfect for development 7 | # since you don't have to restart the web server when you make code changes. 8 | config.cache_classes = false 9 | 10 | # Show full error reports and disable caching 11 | config.consider_all_requests_local = true 12 | config.action_controller.perform_caching = false 13 | 14 | # Don't care if the mailer can't send 15 | config.action_mailer.raise_delivery_errors = false 16 | 17 | # Print deprecation notices to the Rails logger 18 | config.active_support.deprecation = :log 19 | 20 | # Only use best-standards-support built into browsers 21 | config.action_dispatch.best_standards_support = :builtin 22 | 23 | # Do not compress assets 24 | config.assets.compress = false 25 | 26 | # Expands the lines which load the assets 27 | config.assets.debug = true 28 | end 29 | -------------------------------------------------------------------------------- /spec/dummy/config/environments/production.rb: -------------------------------------------------------------------------------- 1 | Dummy::Application.configure do 2 | # Settings specified here will take precedence over those in config/application.rb 3 | config.eager_load = true 4 | 5 | # Code is not reloaded between requests 6 | config.cache_classes = true 7 | 8 | # Full error reports are disabled and caching is turned on 9 | config.consider_all_requests_local = false 10 | config.action_controller.perform_caching = true 11 | 12 | # Disable Rails's static asset server (Apache or nginx will already do this) 13 | config.serve_static_assets = false 14 | 15 | # Compress JavaScripts and CSS 16 | config.assets.compress = true 17 | 18 | # Don't fallback to assets pipeline if a precompiled asset is missed 19 | config.assets.compile = false 20 | 21 | # Generate digests for assets URLs 22 | config.assets.digest = true 23 | 24 | # Defaults to nil and saved in location specified by config.assets.prefix 25 | # config.assets.manifest = YOUR_PATH 26 | 27 | # Specifies the header that your server uses for sending files 28 | # config.action_dispatch.x_sendfile_header = "X-Sendfile" # for apache 29 | # config.action_dispatch.x_sendfile_header = 'X-Accel-Redirect' # for nginx 30 | 31 | # Force all access to the app over SSL, use Strict-Transport-Security, and use secure cookies. 32 | # config.force_ssl = true 33 | 34 | # See everything in the log (default is :info) 35 | # config.log_level = :debug 36 | 37 | # Prepend all log lines with the following tags 38 | # config.log_tags = [ :subdomain, :uuid ] 39 | 40 | # Use a different logger for distributed setups 41 | # config.logger = ActiveSupport::TaggedLogging.new(SyslogLogger.new) 42 | 43 | # Use a different cache store in production 44 | # config.cache_store = :mem_cache_store 45 | 46 | # Enable serving of images, stylesheets, and JavaScripts from an asset server 47 | # config.action_controller.asset_host = "http://assets.example.com" 48 | 49 | # Precompile additional assets (application.js, application.css, and all non-JS/CSS are already added) 50 | # config.assets.precompile += %w( search.js ) 51 | 52 | # Disable delivery errors, bad email addresses will be ignored 53 | # config.action_mailer.raise_delivery_errors = false 54 | 55 | # Enable threaded mode 56 | # config.threadsafe! 57 | 58 | # Enable locale fallbacks for I18n (makes lookups for any locale fall back to 59 | # the I18n.default_locale when a translation can not be found) 60 | config.i18n.fallbacks = true 61 | 62 | # Send deprecation notices to registered listeners 63 | config.active_support.deprecation = :notify 64 | end 65 | -------------------------------------------------------------------------------- /spec/dummy/config/environments/test.rb: -------------------------------------------------------------------------------- 1 | Dummy::Application.configure do 2 | # Settings specified here will take precedence over those in config/application.rb 3 | config.eager_load = false 4 | 5 | # The test environment is used exclusively to run your application's 6 | # test suite. You never need to work with it otherwise. Remember that 7 | # your test database is "scratch space" for the test suite and is wiped 8 | # and recreated between test runs. Don't rely on the data there! 9 | config.cache_classes = true 10 | 11 | # Configure static asset server for tests with Cache-Control for performance 12 | config.serve_static_assets = true 13 | config.static_cache_control = "public, max-age=3600" 14 | 15 | # Show full error reports and disable caching 16 | config.consider_all_requests_local = true 17 | config.action_controller.perform_caching = false 18 | 19 | # Raise exceptions instead of rendering exception templates 20 | config.action_dispatch.show_exceptions = false 21 | 22 | # Disable request forgery protection in test environment 23 | config.action_controller.allow_forgery_protection = false 24 | 25 | # Tell Action Mailer not to deliver emails to the real world. 26 | # The :test delivery method accumulates sent emails in the 27 | # ActionMailer::Base.deliveries array. 28 | config.action_mailer.delivery_method = :test 29 | 30 | # Print deprecation notices to the stderr 31 | config.active_support.deprecation = :stderr 32 | end 33 | -------------------------------------------------------------------------------- /spec/dummy/config/initializers/active_admin.rb: -------------------------------------------------------------------------------- 1 | ActiveAdmin.setup do |config| 2 | 3 | # == Site Title 4 | # 5 | # Set the title that is displayed on the main layout 6 | # for each of the active admin pages. 7 | # 8 | config.site_title = "Dummy" 9 | 10 | # Set the link url for the title. For example, to take 11 | # users to your main site. Defaults to no link. 12 | # 13 | # config.site_title_link = "/" 14 | 15 | # Set an optional image to be displayed for the header 16 | # instead of a string (overrides :site_title) 17 | # 18 | # Note: Recommended image height is 21px to properly fit in the header 19 | # 20 | # config.site_title_image = "/images/logo.png" 21 | 22 | # == Default Namespace 23 | # 24 | # Set the default namespace each administration resource 25 | # will be added to. 26 | # 27 | # eg: 28 | # config.default_namespace = :hello_world 29 | # 30 | # This will create resources in the HelloWorld module and 31 | # will namespace routes to /hello_world/* 32 | # 33 | # To set no namespace by default, use: 34 | # config.default_namespace = false 35 | # 36 | # Default: 37 | # config.default_namespace = :admin 38 | # 39 | # You can customize the settings for each namespace by using 40 | # a namespace block. For example, to change the site title 41 | # within a namespace: 42 | # 43 | # config.namespace :admin do |admin| 44 | # admin.site_title = "Custom Admin Title" 45 | # end 46 | # 47 | # This will ONLY change the title for the admin section. Other 48 | # namespaces will continue to use the main "site_title" configuration. 49 | 50 | # == User Authentication 51 | # 52 | # Active Admin will automatically call an authentication 53 | # method in a before filter of all controller actions to 54 | # ensure that there is a currently logged in admin user. 55 | # 56 | # This setting changes the method which Active Admin calls 57 | # within the controller. 58 | config.authentication_method = :authenticate_admin_user! 59 | 60 | # == User Authorization 61 | # 62 | # Active Admin will automatically call an authorization 63 | # method in a before filter of all controller actions to 64 | # ensure that there is a user with proper rights. You can use 65 | # CanCanAdapter or make your own. Please refer to documentation. 66 | # config.authorization_adapter = ActiveAdmin::CanCanAdapter 67 | 68 | # You can customize your CanCan Ability class name here. 69 | # config.cancan_ability_class = "Ability" 70 | 71 | # You can specify a method to be called on unauthorized access. 72 | # This is necessary in order to prevent a redirect loop which happens 73 | # because, by default, user gets redirected to Dashboard. If user 74 | # doesn't have access to Dashboard, he'll end up in a redirect loop. 75 | # Method provided here should be defined in application_controller.rb. 76 | # config.on_unauthorized_access = :access_denied 77 | 78 | # == Current User 79 | # 80 | # Active Admin will associate actions with the current 81 | # user performing them. 82 | # 83 | # This setting changes the method which Active Admin calls 84 | # to return the currently logged in user. 85 | config.current_user_method = :current_admin_user 86 | 87 | 88 | # == Logging Out 89 | # 90 | # Active Admin displays a logout link on each screen. These 91 | # settings configure the location and method used for the link. 92 | # 93 | # This setting changes the path where the link points to. If it's 94 | # a string, the strings is used as the path. If it's a Symbol, we 95 | # will call the method to return the path. 96 | # 97 | # Default: 98 | config.logout_link_path = :destroy_admin_user_session_path 99 | 100 | # This setting changes the http method used when rendering the 101 | # link. For example :get, :delete, :put, etc.. 102 | # 103 | # Default: 104 | # config.logout_link_method = :get 105 | 106 | 107 | # == Root 108 | # 109 | # Set the action to call for the root path. You can set different 110 | # roots for each namespace. 111 | # 112 | # Default: 113 | # config.root_to = 'dashboard#index' 114 | 115 | 116 | # == Admin Comments 117 | # 118 | # This allows your users to comment on any resource registered with Active Admin. 119 | # 120 | # You can completely disable comments: 121 | # config.allow_comments = false 122 | # 123 | # You can disable the menu item for the comments index page: 124 | # config.show_comments_in_menu = false 125 | # 126 | # You can change the name under which comments are registered: 127 | # config.comments_registration_name = 'AdminComment' 128 | 129 | 130 | # == Batch Actions 131 | # 132 | # Enable and disable Batch Actions 133 | # 134 | config.batch_actions = true 135 | 136 | 137 | # == Controller Filters 138 | # 139 | # You can add before, after and around filters to all of your 140 | # Active Admin resources and pages from here. 141 | # 142 | # config.before_filter :do_something_awesome 143 | 144 | 145 | # == Setting a Favicon 146 | # 147 | # config.favicon = '/assets/favicon.ico' 148 | 149 | 150 | # == Register Stylesheets & Javascripts 151 | # 152 | # We recommend using the built in Active Admin layout and loading 153 | # up your own stylesheets / javascripts to customize the look 154 | # and feel. 155 | # 156 | # To load a stylesheet: 157 | # config.register_stylesheet 'my_stylesheet.css' 158 | # 159 | # You can provide an options hash for more control, which is passed along to stylesheet_link_tag(): 160 | # config.register_stylesheet 'my_print_stylesheet.css', :media => :print 161 | # 162 | # To load a javascript file: 163 | # config.register_javascript 'my_javascript.js' 164 | 165 | 166 | # == CSV options 167 | # 168 | # Set the CSV builder separator 169 | # config.csv_options = { :col_sep => ';' } 170 | # 171 | # Force the use of quotes 172 | # config.csv_options = { :force_quotes => true } 173 | 174 | 175 | # == Menu System 176 | # 177 | # You can add a navigation menu to be used in your application, or configure a provided menu 178 | # 179 | # To change the default utility navigation to show a link to your website & a logout btn 180 | # 181 | # config.namespace :admin do |admin| 182 | # admin.build_menu :utility_navigation do |menu| 183 | # menu.add label: "My Great Website", url: "http://www.mygreatwebsite.com", html_options: { target: :blank } 184 | # admin.add_logout_button_to_menu menu 185 | # end 186 | # end 187 | # 188 | # If you wanted to add a static menu item to the default menu provided: 189 | # 190 | # config.namespace :admin do |admin| 191 | # admin.build_menu :default do |menu| 192 | # menu.add label: "My Great Website", url: "http://www.mygreatwebsite.com", html_options: { target: :blank } 193 | # end 194 | # end 195 | 196 | 197 | # == Download Links 198 | # 199 | # You can disable download links on resource listing pages, 200 | # or customize the formats shown per namespace/globally 201 | # 202 | # To disable/customize for the :admin namespace: 203 | # 204 | # config.namespace :admin do |admin| 205 | # 206 | # # Disable the links entirely 207 | # admin.download_links = false 208 | # 209 | # # Only show XML & PDF options 210 | # admin.download_links = [:xml, :pdf] 211 | # 212 | # end 213 | 214 | 215 | # == Pagination 216 | # 217 | # Pagination is enabled by default for all resources. 218 | # You can control the default per page count for all resources here. 219 | # 220 | # config.default_per_page = 30 221 | 222 | 223 | # == Filters 224 | # 225 | # By default the index screen includes a “Filters” sidebar on the right 226 | # hand side with a filter for each attribute of the registered model. 227 | # You can enable or disable them for all resources here. 228 | # 229 | # config.filters = true 230 | 231 | end 232 | -------------------------------------------------------------------------------- /spec/dummy/config/initializers/backtrace_silencers.rb: -------------------------------------------------------------------------------- 1 | # Be sure to restart your server when you modify this file. 2 | 3 | # You can add backtrace silencers for libraries that you're using but don't wish to see in your backtraces. 4 | # Rails.backtrace_cleaner.add_silencer { |line| line =~ /my_noisy_library/ } 5 | 6 | # You can also remove all the silencers if you're trying to debug a problem that might stem from framework code. 7 | # Rails.backtrace_cleaner.remove_silencers! 8 | -------------------------------------------------------------------------------- /spec/dummy/config/initializers/devise.rb: -------------------------------------------------------------------------------- 1 | # Use this hook to configure devise mailer, warden hooks and so forth. 2 | # Many of these configuration options can be set straight in your model. 3 | Devise.setup do |config| 4 | # The secret key used by Devise. Devise uses this key to generate 5 | # random tokens. Changing this key will render invalid all existing 6 | # confirmation, reset password and unlock tokens in the database. 7 | config.secret_key = 'b0fbbf8e3570d384d99533e27d054134a100b3f5070d22aa7484b3fa541f86789337763290fe0ca491ba38e8476148a6010981c4c8ce0f8e22f49fc8bbe4bbec' 8 | 9 | # ==> Mailer Configuration 10 | # Configure the e-mail address which will be shown in Devise::Mailer, 11 | # note that it will be overwritten if you use your own mailer class 12 | # with default "from" parameter. 13 | config.mailer_sender = 'please-change-me-at-config-initializers-devise@example.com' 14 | 15 | # Configure the class responsible to send e-mails. 16 | # config.mailer = 'Devise::Mailer' 17 | 18 | # ==> ORM configuration 19 | # Load and configure the ORM. Supports :active_record (default) and 20 | # :mongoid (bson_ext recommended) by default. Other ORMs may be 21 | # available as additional gems. 22 | require 'devise/orm/active_record' 23 | 24 | # ==> Configuration for any authentication mechanism 25 | # Configure which keys are used when authenticating a user. The default is 26 | # just :email. You can configure it to use [:username, :subdomain], so for 27 | # authenticating a user, both parameters are required. Remember that those 28 | # parameters are used only when authenticating and not when retrieving from 29 | # session. If you need permissions, you should implement that in a before filter. 30 | # You can also supply a hash where the value is a boolean determining whether 31 | # or not authentication should be aborted when the value is not present. 32 | # config.authentication_keys = [ :email ] 33 | 34 | # Configure parameters from the request object used for authentication. Each entry 35 | # given should be a request method and it will automatically be passed to the 36 | # find_for_authentication method and considered in your model lookup. For instance, 37 | # if you set :request_keys to [:subdomain], :subdomain will be used on authentication. 38 | # The same considerations mentioned for authentication_keys also apply to request_keys. 39 | # config.request_keys = [] 40 | 41 | # Configure which authentication keys should be case-insensitive. 42 | # These keys will be downcased upon creating or modifying a user and when used 43 | # to authenticate or find a user. Default is :email. 44 | config.case_insensitive_keys = [ :email ] 45 | 46 | # Configure which authentication keys should have whitespace stripped. 47 | # These keys will have whitespace before and after removed upon creating or 48 | # modifying a user and when used to authenticate or find a user. Default is :email. 49 | config.strip_whitespace_keys = [ :email ] 50 | 51 | # Tell if authentication through request.params is enabled. True by default. 52 | # It can be set to an array that will enable params authentication only for the 53 | # given strategies, for example, `config.params_authenticatable = [:database]` will 54 | # enable it only for database (email + password) authentication. 55 | # config.params_authenticatable = true 56 | 57 | # Tell if authentication through HTTP Auth is enabled. False by default. 58 | # It can be set to an array that will enable http authentication only for the 59 | # given strategies, for example, `config.http_authenticatable = [:database]` will 60 | # enable it only for database authentication. The supported strategies are: 61 | # :database = Support basic authentication with authentication key + password 62 | # config.http_authenticatable = false 63 | 64 | # If http headers should be returned for AJAX requests. True by default. 65 | # config.http_authenticatable_on_xhr = true 66 | 67 | # The realm used in Http Basic Authentication. 'Application' by default. 68 | # config.http_authentication_realm = 'Application' 69 | 70 | # It will change confirmation, password recovery and other workflows 71 | # to behave the same regardless if the e-mail provided was right or wrong. 72 | # Does not affect registerable. 73 | # config.paranoid = true 74 | 75 | # By default Devise will store the user in session. You can skip storage for 76 | # particular strategies by setting this option. 77 | # Notice that if you are skipping storage for all authentication paths, you 78 | # may want to disable generating routes to Devise's sessions controller by 79 | # passing skip: :sessions to `devise_for` in your config/routes.rb 80 | config.skip_session_storage = [:http_auth] 81 | 82 | # By default, Devise cleans up the CSRF token on authentication to 83 | # avoid CSRF token fixation attacks. This means that, when using AJAX 84 | # requests for sign in and sign up, you need to get a new CSRF token 85 | # from the server. You can disable this option at your own risk. 86 | # config.clean_up_csrf_token_on_authentication = true 87 | 88 | # ==> Configuration for :database_authenticatable 89 | # For bcrypt, this is the cost for hashing the password and defaults to 10. If 90 | # using other encryptors, it sets how many times you want the password re-encrypted. 91 | # 92 | # Limiting the stretches to just one in testing will increase the performance of 93 | # your test suite dramatically. However, it is STRONGLY RECOMMENDED to not use 94 | # a value less than 10 in other environments. Note that, for bcrypt (the default 95 | # encryptor), the cost increases exponentially with the number of stretches (e.g. 96 | # a value of 20 is already extremely slow: approx. 60 seconds for 1 calculation). 97 | config.stretches = Rails.env.test? ? 1 : 10 98 | 99 | # Setup a pepper to generate the encrypted password. 100 | # config.pepper = '02b4d097f34d643b4c408483308061085c5dbe84119f998c51bf0f56ea5410851bcc685f5074e4518c90c3ea94266a909cc44d26671ad135ff9b511f80f1969d' 101 | 102 | # ==> Configuration for :confirmable 103 | # A period that the user is allowed to access the website even without 104 | # confirming their account. For instance, if set to 2.days, the user will be 105 | # able to access the website for two days without confirming their account, 106 | # access will be blocked just in the third day. Default is 0.days, meaning 107 | # the user cannot access the website without confirming their account. 108 | # config.allow_unconfirmed_access_for = 2.days 109 | 110 | # A period that the user is allowed to confirm their account before their 111 | # token becomes invalid. For example, if set to 3.days, the user can confirm 112 | # their account within 3 days after the mail was sent, but on the fourth day 113 | # their account can't be confirmed with the token any more. 114 | # Default is nil, meaning there is no restriction on how long a user can take 115 | # before confirming their account. 116 | # config.confirm_within = 3.days 117 | 118 | # If true, requires any email changes to be confirmed (exactly the same way as 119 | # initial account confirmation) to be applied. Requires additional unconfirmed_email 120 | # db field (see migrations). Until confirmed, new email is stored in 121 | # unconfirmed_email column, and copied to email column on successful confirmation. 122 | config.reconfirmable = true 123 | 124 | # Defines which key will be used when confirming an account 125 | # config.confirmation_keys = [ :email ] 126 | 127 | # ==> Configuration for :rememberable 128 | # The time the user will be remembered without asking for credentials again. 129 | # config.remember_for = 2.weeks 130 | 131 | # If true, extends the user's remember period when remembered via cookie. 132 | # config.extend_remember_period = false 133 | 134 | # Options to be passed to the created cookie. For instance, you can set 135 | # secure: true in order to force SSL only cookies. 136 | # config.rememberable_options = {} 137 | 138 | # ==> Configuration for :validatable 139 | # Range for password length. 140 | config.password_length = 8..128 141 | 142 | # Email regex used to validate email formats. It simply asserts that 143 | # one (and only one) @ exists in the given string. This is mainly 144 | # to give user feedback and not to assert the e-mail validity. 145 | # config.email_regexp = /\A[^@]+@[^@]+\z/ 146 | 147 | # ==> Configuration for :timeoutable 148 | # The time you want to timeout the user session without activity. After this 149 | # time the user will be asked for credentials again. Default is 30 minutes. 150 | # config.timeout_in = 30.minutes 151 | 152 | # If true, expires auth token on session timeout. 153 | # config.expire_auth_token_on_timeout = false 154 | 155 | # ==> Configuration for :lockable 156 | # Defines which strategy will be used to lock an account. 157 | # :failed_attempts = Locks an account after a number of failed attempts to sign in. 158 | # :none = No lock strategy. You should handle locking by yourself. 159 | # config.lock_strategy = :failed_attempts 160 | 161 | # Defines which key will be used when locking and unlocking an account 162 | # config.unlock_keys = [ :email ] 163 | 164 | # Defines which strategy will be used to unlock an account. 165 | # :email = Sends an unlock link to the user email 166 | # :time = Re-enables login after a certain amount of time (see :unlock_in below) 167 | # :both = Enables both strategies 168 | # :none = No unlock strategy. You should handle unlocking by yourself. 169 | # config.unlock_strategy = :both 170 | 171 | # Number of authentication tries before locking an account if lock_strategy 172 | # is failed attempts. 173 | # config.maximum_attempts = 20 174 | 175 | # Time interval to unlock the account if :time is enabled as unlock_strategy. 176 | # config.unlock_in = 1.hour 177 | 178 | # Warn on the last attempt before the account is locked. 179 | # config.last_attempt_warning = false 180 | 181 | # ==> Configuration for :recoverable 182 | # 183 | # Defines which key will be used when recovering the password for an account 184 | # config.reset_password_keys = [ :email ] 185 | 186 | # Time interval you can reset your password with a reset password key. 187 | # Don't put a too small interval or your users won't have the time to 188 | # change their passwords. 189 | config.reset_password_within = 6.hours 190 | 191 | # ==> Configuration for :encryptable 192 | # Allow you to use another encryption algorithm besides bcrypt (default). You can use 193 | # :sha1, :sha512 or encryptors from others authentication tools as :clearance_sha1, 194 | # :authlogic_sha512 (then you should set stretches above to 20 for default behavior) 195 | # and :restful_authentication_sha1 (then you should set stretches to 10, and copy 196 | # REST_AUTH_SITE_KEY to pepper). 197 | # 198 | # Require the `devise-encryptable` gem when using anything other than bcrypt 199 | # config.encryptor = :sha512 200 | 201 | # ==> Scopes configuration 202 | # Turn scoped views on. Before rendering "sessions/new", it will first check for 203 | # "users/sessions/new". It's turned off by default because it's slower if you 204 | # are using only default views. 205 | # config.scoped_views = false 206 | 207 | # Configure the default scope given to Warden. By default it's the first 208 | # devise role declared in your routes (usually :user). 209 | # config.default_scope = :user 210 | 211 | # Set this configuration to false if you want /users/sign_out to sign out 212 | # only the current scope. By default, Devise signs out all scopes. 213 | # config.sign_out_all_scopes = true 214 | 215 | # ==> Navigation configuration 216 | # Lists the formats that should be treated as navigational. Formats like 217 | # :html, should redirect to the sign in page when the user does not have 218 | # access, but formats like :xml or :json, should return 401. 219 | # 220 | # If you have any extra navigational formats, like :iphone or :mobile, you 221 | # should add them to the navigational formats lists. 222 | # 223 | # The "*/*" below is required to match Internet Explorer requests. 224 | # config.navigational_formats = ['*/*', :html] 225 | 226 | # The default HTTP method used to sign out a resource. Default is :delete. 227 | config.sign_out_via = :delete 228 | 229 | # ==> OmniAuth 230 | # Add a new OmniAuth provider. Check the wiki for more information on setting 231 | # up on your models and hooks. 232 | # config.omniauth :github, 'APP_ID', 'APP_SECRET', scope: 'user,public_repo' 233 | 234 | # ==> Warden configuration 235 | # If you want to use other strategies, that are not supported by Devise, or 236 | # change the failure app, you can configure them inside the config.warden block. 237 | # 238 | # config.warden do |manager| 239 | # manager.intercept_401 = false 240 | # manager.default_strategies(scope: :user).unshift :some_external_strategy 241 | # end 242 | 243 | # ==> Mountable engine configurations 244 | # When using Devise inside an engine, let's call it `MyEngine`, and this engine 245 | # is mountable, there are some extra configurations to be taken into account. 246 | # The following options are available, assuming the engine is mounted as: 247 | # 248 | # mount MyEngine, at: '/my_engine' 249 | # 250 | # The router that invoked `devise_for`, in the example above, would be: 251 | # config.router_name = :my_engine 252 | # 253 | # When using omniauth, Devise cannot automatically set Omniauth path, 254 | # so you need to do it manually. For the users scope, it would be: 255 | # config.omniauth_path_prefix = '/my_engine/users/auth' 256 | end 257 | -------------------------------------------------------------------------------- /spec/dummy/config/initializers/inflections.rb: -------------------------------------------------------------------------------- 1 | # Be sure to restart your server when you modify this file. 2 | 3 | # Add new inflection rules using the following format 4 | # (all these examples are active by default): 5 | # ActiveSupport::Inflector.inflections do |inflect| 6 | # inflect.plural /^(ox)$/i, '\1en' 7 | # inflect.singular /^(ox)en/i, '\1' 8 | # inflect.irregular 'person', 'people' 9 | # inflect.uncountable %w( fish sheep ) 10 | # end 11 | # 12 | # These inflection rules are supported but not enabled by default: 13 | # ActiveSupport::Inflector.inflections do |inflect| 14 | # inflect.acronym 'RESTful' 15 | # end 16 | -------------------------------------------------------------------------------- /spec/dummy/config/initializers/mime_types.rb: -------------------------------------------------------------------------------- 1 | # Be sure to restart your server when you modify this file. 2 | 3 | # Add new mime types for use in respond_to blocks: 4 | # Mime::Type.register "text/richtext", :rtf 5 | # Mime::Type.register_alias "text/html", :iphone 6 | -------------------------------------------------------------------------------- /spec/dummy/config/initializers/secret_token.rb: -------------------------------------------------------------------------------- 1 | # no regular words or you'll be exposed to dictionary attacks. 2 | 3 | token = '9bf407e3407d9e3ae5a7739f8927f80a04b7f376dc1e23de9ae783f03ff0f53df35aa9d1f72e3d0fb1096d29b53f84b1c49b6f4165c66f16bfadf9f1d3b518ad' 4 | if ENV['RAILS_VERSION'] == "3.2" 5 | Dummy::Application.config.secret_token = token 6 | else 7 | Dummy::Application.config.secret_key_base = token 8 | end 9 | -------------------------------------------------------------------------------- /spec/dummy/config/initializers/session_store.rb: -------------------------------------------------------------------------------- 1 | # Be sure to restart your server when you modify this file. 2 | 3 | Dummy::Application.config.session_store :cookie_store, key: '_dummy_session' 4 | 5 | # Use the database for sessions instead of the cookie-based default, 6 | # which shouldn't be used to store highly confidential information 7 | # (create the session table with "rails generate session_migration") 8 | # Dummy::Application.config.session_store :active_record_store 9 | -------------------------------------------------------------------------------- /spec/dummy/config/initializers/wrap_parameters.rb: -------------------------------------------------------------------------------- 1 | # Be sure to restart your server when you modify this file. 2 | # 3 | # This file contains settings for ActionController::ParamsWrapper which 4 | # is enabled by default. 5 | 6 | # Enable parameter wrapping for JSON. You can disable this by setting :format to an empty array. 7 | ActiveSupport.on_load(:action_controller) do 8 | wrap_parameters format: [:json] 9 | end 10 | 11 | # Disable root element in JSON by default. 12 | ActiveSupport.on_load(:active_record) do 13 | self.include_root_in_json = false 14 | end 15 | -------------------------------------------------------------------------------- /spec/dummy/config/locales/devise.en.yml: -------------------------------------------------------------------------------- 1 | # Additional translations at https://github.com/plataformatec/devise/wiki/I18n 2 | 3 | en: 4 | devise: 5 | confirmations: 6 | confirmed: "Your account was successfully confirmed." 7 | send_instructions: "You will receive an email with instructions about how to confirm your account in a few minutes." 8 | send_paranoid_instructions: "If your email address exists in our database, you will receive an email with instructions about how to confirm your account in a few minutes." 9 | failure: 10 | already_authenticated: "You are already signed in." 11 | inactive: "Your account is not activated yet." 12 | invalid: "Invalid email or password." 13 | locked: "Your account is locked." 14 | last_attempt: "You have one more attempt before your account will be locked." 15 | not_found_in_database: "Invalid email or password." 16 | timeout: "Your session expired. Please sign in again to continue." 17 | unauthenticated: "You need to sign in or sign up before continuing." 18 | unconfirmed: "You have to confirm your account before continuing." 19 | mailer: 20 | confirmation_instructions: 21 | subject: "Confirmation instructions" 22 | reset_password_instructions: 23 | subject: "Reset password instructions" 24 | unlock_instructions: 25 | subject: "Unlock Instructions" 26 | omniauth_callbacks: 27 | failure: "Could not authenticate you from %{kind} because \"%{reason}\"." 28 | success: "Successfully authenticated from %{kind} account." 29 | passwords: 30 | no_token: "You can't access this page without coming from a password reset email. If you do come from a password reset email, please make sure you used the full URL provided." 31 | send_instructions: "You will receive an email with instructions on how to reset your password in a few minutes." 32 | send_paranoid_instructions: "If your email address exists in our database, you will receive a password recovery link at your email address in a few minutes." 33 | updated: "Your password was changed successfully. You are now signed in." 34 | updated_not_active: "Your password was changed successfully." 35 | registrations: 36 | destroyed: "Bye! Your account was successfully cancelled. We hope to see you again soon." 37 | signed_up: "Welcome! You have signed up successfully." 38 | signed_up_but_inactive: "You have signed up successfully. However, we could not sign you in because your account is not yet activated." 39 | signed_up_but_locked: "You have signed up successfully. However, we could not sign you in because your account is locked." 40 | signed_up_but_unconfirmed: "A message with a confirmation link has been sent to your email address. Please open the link to activate your account." 41 | update_needs_confirmation: "You updated your account successfully, but we need to verify your new email address. Please check your email and click on the confirm link to finalize confirming your new email address." 42 | updated: "You updated your account successfully." 43 | sessions: 44 | signed_in: "Signed in successfully." 45 | signed_out: "Signed out successfully." 46 | unlocks: 47 | send_instructions: "You will receive an email with instructions about how to unlock your account in a few minutes." 48 | send_paranoid_instructions: "If your account exists, you will receive an email with instructions about how to unlock it in a few minutes." 49 | unlocked: "Your account has been unlocked successfully. Please sign in to continue." 50 | errors: 51 | messages: 52 | already_confirmed: "was already confirmed, please try signing in" 53 | confirmation_period_expired: "needs to be confirmed within %{period}, please request a new one" 54 | expired: "has expired, please request a new one" 55 | not_found: "not found" 56 | not_locked: "was not locked" 57 | not_saved: 58 | one: "1 error prohibited this %{resource} from being saved:" 59 | other: "%{count} errors prohibited this %{resource} from being saved:" 60 | -------------------------------------------------------------------------------- /spec/dummy/config/locales/en.yml: -------------------------------------------------------------------------------- 1 | # Sample localization file for English. Add more files in this directory for other locales. 2 | # See https://github.com/svenfuchs/rails-i18n/tree/master/rails%2Flocale for starting points. 3 | 4 | en: 5 | hello: "Hello world" 6 | -------------------------------------------------------------------------------- /spec/dummy/config/routes.rb: -------------------------------------------------------------------------------- 1 | Dummy::Application.routes.draw do 2 | devise_for :admin_users, ActiveAdmin::Devise.config 3 | ActiveAdmin.routes(self) 4 | 5 | # The priority is based upon order of creation: 6 | # first created -> highest priority. 7 | 8 | # Sample of regular route: 9 | # match 'products/:id' => 'catalog#view' 10 | # Keep in mind you can assign values other than :controller and :action 11 | 12 | # Sample of named route: 13 | # match 'products/:id/purchase' => 'catalog#purchase', :as => :purchase 14 | # This route can be invoked with purchase_url(:id => product.id) 15 | 16 | # Sample resource route (maps HTTP verbs to controller actions automatically): 17 | # resources :products 18 | 19 | # Sample resource route with options: 20 | # resources :products do 21 | # member do 22 | # get 'short' 23 | # post 'toggle' 24 | # end 25 | # 26 | # collection do 27 | # get 'sold' 28 | # end 29 | # end 30 | 31 | # Sample resource route with sub-resources: 32 | # resources :products do 33 | # resources :comments, :sales 34 | # resource :seller 35 | # end 36 | 37 | # Sample resource route with more complex sub-resources 38 | # resources :products do 39 | # resources :comments 40 | # resources :sales do 41 | # get 'recent', :on => :collection 42 | # end 43 | # end 44 | 45 | # Sample resource route within a namespace: 46 | # namespace :admin do 47 | # # Directs /admin/products/* to Admin::ProductsController 48 | # # (app/controllers/admin/products_controller.rb) 49 | # resources :products 50 | # end 51 | 52 | # You can have the root of your site routed with "root" 53 | # just remember to delete public/index.html. 54 | # root :to => 'welcome#index' 55 | 56 | # See how all your routes lay out with "rake routes" 57 | 58 | # This is a legacy wild controller route that's not recommended for RESTful applications. 59 | # Note: This route will make all actions in every controller accessible via GET requests. 60 | # match ':controller(/:action(/:id))(.:format)' 61 | end 62 | -------------------------------------------------------------------------------- /spec/dummy/db/migrate/20140806024135_devise_create_admin_users.rb: -------------------------------------------------------------------------------- 1 | class DeviseCreateAdminUsers < ActiveRecord::Migration 2 | def migrate(direction) 3 | super 4 | # Create a default user 5 | AdminUser.create!(:email => 'admin@example.com', :password => 'password', :password_confirmation => 'password') if direction == :up 6 | end 7 | 8 | def change 9 | create_table(:admin_users) do |t| 10 | ## Database authenticatable 11 | t.string :email, null: false, default: "" 12 | t.string :encrypted_password, null: false, default: "" 13 | 14 | ## Recoverable 15 | t.string :reset_password_token 16 | t.datetime :reset_password_sent_at 17 | 18 | ## Rememberable 19 | t.datetime :remember_created_at 20 | 21 | ## Trackable 22 | t.integer :sign_in_count, default: 0, null: false 23 | t.datetime :current_sign_in_at 24 | t.datetime :last_sign_in_at 25 | t.string :current_sign_in_ip 26 | t.string :last_sign_in_ip 27 | 28 | ## Confirmable 29 | # t.string :confirmation_token 30 | # t.datetime :confirmed_at 31 | # t.datetime :confirmation_sent_at 32 | # t.string :unconfirmed_email # Only if using reconfirmable 33 | 34 | ## Lockable 35 | # t.integer :failed_attempts, default: 0, null: false # Only if lock strategy is :failed_attempts 36 | # t.string :unlock_token # Only if unlock strategy is :email or :both 37 | # t.datetime :locked_at 38 | 39 | 40 | t.timestamps 41 | end 42 | 43 | add_index :admin_users, :email, unique: true 44 | add_index :admin_users, :reset_password_token, unique: true 45 | # add_index :admin_users, :confirmation_token, unique: true 46 | # add_index :admin_users, :unlock_token, unique: true 47 | end 48 | end 49 | -------------------------------------------------------------------------------- /spec/dummy/db/migrate/20140806024139_create_active_admin_comments.rb: -------------------------------------------------------------------------------- 1 | class CreateActiveAdminComments < ActiveRecord::Migration 2 | def self.up 3 | create_table :active_admin_comments do |t| 4 | t.string :namespace 5 | t.text :body 6 | t.string :resource_id, :null => false 7 | t.string :resource_type, :null => false 8 | t.references :author, :polymorphic => true 9 | t.timestamps 10 | end 11 | add_index :active_admin_comments, [:namespace] 12 | add_index :active_admin_comments, [:author_type, :author_id] 13 | add_index :active_admin_comments, [:resource_type, :resource_id] 14 | end 15 | 16 | def self.down 17 | drop_table :active_admin_comments 18 | end 19 | end 20 | -------------------------------------------------------------------------------- /spec/dummy/db/migrate/20140806032156_create_categories.rb: -------------------------------------------------------------------------------- 1 | class CreateCategories < ActiveRecord::Migration 2 | def change 3 | create_table :categories do |t| 4 | t.string :name 5 | t.string :ancestry 6 | t.string :description 7 | t.integer :position 8 | 9 | t.timestamps 10 | end 11 | end 12 | end 13 | -------------------------------------------------------------------------------- /spec/dummy/db/schema.rb: -------------------------------------------------------------------------------- 1 | # encoding: UTF-8 2 | # This file is auto-generated from the current state of the database. Instead 3 | # of editing this file, please use the migrations feature of Active Record to 4 | # incrementally modify your database, and then regenerate this schema definition. 5 | # 6 | # Note that this schema.rb definition is the authoritative source for your 7 | # database schema. If you need to create the application database on another 8 | # system, you should be using db:schema:load, not running all the migrations 9 | # from scratch. The latter is a flawed and unsustainable approach (the more migrations 10 | # you'll amass, the slower it'll run and the greater likelihood for issues). 11 | # 12 | # It's strongly recommended to check this file into your version control system. 13 | 14 | ActiveRecord::Schema.define(:version => 20140806032156) do 15 | 16 | create_table "active_admin_comments", :force => true do |t| 17 | t.string "namespace" 18 | t.text "body" 19 | t.string "resource_id", :null => false 20 | t.string "resource_type", :null => false 21 | t.integer "author_id" 22 | t.string "author_type" 23 | t.datetime "created_at", :null => false 24 | t.datetime "updated_at", :null => false 25 | end 26 | 27 | add_index "active_admin_comments", ["author_type", "author_id"], :name => "index_active_admin_comments_on_author_type_and_author_id" 28 | add_index "active_admin_comments", ["namespace"], :name => "index_active_admin_comments_on_namespace" 29 | add_index "active_admin_comments", ["resource_type", "resource_id"], :name => "index_active_admin_comments_on_resource_type_and_resource_id" 30 | 31 | create_table "admin_users", :force => true do |t| 32 | t.string "email", :default => "", :null => false 33 | t.string "encrypted_password", :default => "", :null => false 34 | t.string "reset_password_token" 35 | t.datetime "reset_password_sent_at" 36 | t.datetime "remember_created_at" 37 | t.integer "sign_in_count", :default => 0, :null => false 38 | t.datetime "current_sign_in_at" 39 | t.datetime "last_sign_in_at" 40 | t.string "current_sign_in_ip" 41 | t.string "last_sign_in_ip" 42 | t.datetime "created_at", :null => false 43 | t.datetime "updated_at", :null => false 44 | end 45 | 46 | add_index "admin_users", ["email"], :name => "index_admin_users_on_email", :unique => true 47 | add_index "admin_users", ["reset_password_token"], :name => "index_admin_users_on_reset_password_token", :unique => true 48 | 49 | create_table "categories", :force => true do |t| 50 | t.string "name" 51 | t.string "ancestry" 52 | t.string "description" 53 | t.integer "position" 54 | t.datetime "created_at", :null => false 55 | t.datetime "updated_at", :null => false 56 | end 57 | 58 | end 59 | -------------------------------------------------------------------------------- /spec/dummy/db/seeds.rb: -------------------------------------------------------------------------------- 1 | 2 | if AdminUser.find_by(email: "admin@example.com").nil? 3 | AdminUser.create!(email: "admin@example.com", password: "testing123", password_confirmation: "testing123") 4 | end 5 | 6 | categories = %w[Fruit Apple Pear Watermelon Vegetables Cucumber Squash Onion] 7 | 8 | categories.each do |name| 9 | Category.find_or_create_by!(name: name) 10 | end 11 | -------------------------------------------------------------------------------- /spec/dummy/lib/assets/.gitkeep: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/zorab47/active_admin-sortable_tree/7f2b0fb7f407a526265182303da67a4457c05c31/spec/dummy/lib/assets/.gitkeep -------------------------------------------------------------------------------- /spec/dummy/log/.gitkeep: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/zorab47/active_admin-sortable_tree/7f2b0fb7f407a526265182303da67a4457c05c31/spec/dummy/log/.gitkeep -------------------------------------------------------------------------------- /spec/dummy/public/404.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | The page you were looking for doesn't exist (404) 5 | 17 | 18 | 19 | 20 | 21 |
22 |

The page you were looking for doesn't exist.

23 |

You may have mistyped the address or the page may have moved.

24 |
25 | 26 | 27 | -------------------------------------------------------------------------------- /spec/dummy/public/422.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | The change you wanted was rejected (422) 5 | 17 | 18 | 19 | 20 | 21 |
22 |

The change you wanted was rejected.

23 |

Maybe you tried to change something you didn't have access to.

24 |
25 | 26 | 27 | -------------------------------------------------------------------------------- /spec/dummy/public/500.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | We're sorry, but something went wrong (500) 5 | 17 | 18 | 19 | 20 | 21 |
22 |

We're sorry, but something went wrong.

23 |
24 | 25 | 26 | -------------------------------------------------------------------------------- /spec/dummy/public/favicon.ico: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/zorab47/active_admin-sortable_tree/7f2b0fb7f407a526265182303da67a4457c05c31/spec/dummy/public/favicon.ico -------------------------------------------------------------------------------- /spec/dummy/script/rails: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env ruby 2 | # This command will automatically be run when you run "rails" with Rails 3 gems installed from the root of your application. 3 | 4 | APP_PATH = File.expand_path('../../config/application', __FILE__) 5 | require File.expand_path('../../config/boot', __FILE__) 6 | require 'rails/commands' 7 | -------------------------------------------------------------------------------- /spec/features/sortable_spec.rb: -------------------------------------------------------------------------------- 1 | require 'rails_helper' 2 | 3 | RSpec.describe "ActiveAdmin::SortableTree", type: :feature do 4 | context "configured as sortable" do 5 | it "sorts by dragging vertically", js: true do 6 | bottom = Category.create! name: "bottom", position: 0 7 | top = Category.create! name: "top", position: 1 8 | middle = Category.create! name: "middle", position: 2 9 | 10 | visit admin_categories_path 11 | 12 | expect(all(".ui-sortable li h3").map(&:text)).to eq(["bottom", "top", "middle"]) 13 | 14 | wait_for_ajax { drag_element("#category_#{middle.id} h3", dy: -100) } 15 | wait_for_ajax { drag_element("#category_#{top.id} h3", dy: -100) } 16 | 17 | expect(all(".ui-sortable li h3").map(&:text)).to eq(["top", "middle", "bottom"]) 18 | expect(Category.order(:position).map(&:name)).to eq(["top", "middle", "bottom"]) 19 | end 20 | end 21 | 22 | context "configured as sortable tree" do 23 | it "sorts by dragging vertically", js: true do 24 | bottom = Category.create! name: "bottom", position: 0 25 | top = Category.create! name: "top", position: 1 26 | middle = Category.create! name: "middle", position: 2 27 | 28 | visit admin_category_trees_path 29 | 30 | expect(all(".ui-sortable li h3").map(&:text)).to eq(["bottom", "top", "middle"]) 31 | 32 | wait_for_ajax { drag_element("#category_tree_#{middle.id} h3", dy: -100) } 33 | wait_for_ajax { drag_element("#category_tree_#{top.id} h3", dy: -100) } 34 | 35 | expect(all(".ui-sortable li h3").map(&:text)).to eq(["top", "middle", "bottom"]) 36 | expect(Category.order(:position).map(&:name)).to eq(["top", "middle", "bottom"]) 37 | end 38 | 39 | it "assigns hierarchy by dragging horizontally", js: true do 40 | top = Category.create! name: "top", position: 0 41 | middle = Category.create! name: "middle", position: 1 42 | bottom = Category.create! name: "bottom", position: 2 43 | expect(top.children).not_to include(middle) 44 | 45 | visit admin_category_trees_path 46 | 47 | wait_for_ajax { drag_element("#category_tree_#{middle.id} h3", dx: 40) } 48 | wait_for_ajax { drag_element("#category_tree_#{bottom.id} h3", dx: 40) } 49 | 50 | expect(top.children).to include(middle, bottom) 51 | end 52 | end 53 | 54 | context "with option `sortable: false`" do 55 | it "disables sorting by excluding sortable data attributes" do 56 | bottom = Category.create! name: "bottom", position: 0 57 | top = Category.create! name: "top", position: 1 58 | middle = Category.create! name: "middle", position: 2 59 | 60 | visit admin_category_disabled_sorts_path 61 | 62 | expect(page).to have_css(".index_as_sortable") 63 | expect(page).not_to have_css("[data-sortable-type]") 64 | expect(page).not_to have_css("[data-sortable-url]") 65 | end 66 | 67 | context "with a proc returning false as sortable option" do 68 | it "disables sorting" do 69 | proc_evaluated_within_controller = false 70 | 71 | sortable_options_for("CategoryDisabledSort")[:sortable] = proc do 72 | proc_evaluated_within_controller = self.is_a?(ActiveAdmin::ResourceController) 73 | false 74 | end 75 | 76 | bottom = Category.create! name: "bottom", position: 0 77 | 78 | visit admin_category_disabled_sorts_path 79 | 80 | expect(page).to have_css(".index_as_sortable") 81 | expect(page).not_to have_css("[data-sortable-type]") 82 | expect(proc_evaluated_within_controller).to be true 83 | end 84 | end 85 | end 86 | 87 | def drag_element(selector, options) 88 | options.reverse_merge! moves: 20 89 | page.execute_script(%Q($("#{selector}").simulate("drag", #{options.to_json} ))) 90 | end 91 | 92 | def sortable_options_for(resource) 93 | resource_config = ActiveAdmin.application.namespace(:admin).resource_for(resource) 94 | resource_config.dsl.sortable_options 95 | end 96 | end 97 | -------------------------------------------------------------------------------- /spec/rails_helper.rb: -------------------------------------------------------------------------------- 1 | # This file is copied to spec/ when you run 'rails generate rspec:install' 2 | ENV["RAILS_ENV"] ||= 'test' 3 | require 'spec_helper' 4 | 5 | require File.expand_path('../dummy/config/environment', __FILE__) 6 | 7 | require 'rspec/rails' 8 | require 'capybara/rails' 9 | require 'phantomjs/poltergeist' 10 | require 'database_cleaner' 11 | 12 | Capybara.javascript_driver = :poltergeist 13 | 14 | def reload_menus! 15 | if Float(ENV['RAILS_VERSION']) >= 4.0 16 | ActiveAdmin.application.namespaces.each { |n| n.reset_menu! } 17 | else 18 | ActiveAdmin.application.namespaces.values.each { |n| n.reset_menu! } 19 | end 20 | end 21 | 22 | def reload_routes! 23 | Rails.application.reload_routes! 24 | end 25 | 26 | # Setup ActiveAdmin 27 | ActiveAdmin.application.load_paths = [File.expand_path("../dummy/app/admin", __FILE__)] 28 | ActiveAdmin.unload! 29 | ActiveAdmin.load! 30 | reload_menus! 31 | reload_routes! 32 | 33 | # Disabling authentication in specs so that we don't have to worry about 34 | # it allover the place 35 | ActiveAdmin.application.authentication_method = false 36 | ActiveAdmin.application.current_user_method = false 37 | 38 | Dir[File.expand_path("../support/**/*.rb", __FILE__)].each { |f| require f } 39 | 40 | RSpec.configure do |config| 41 | # Remove this line if you're not using ActiveRecord or ActiveRecord fixtures 42 | config.fixture_path = "#{::Rails.root}/spec/fixtures" 43 | 44 | # If you're not using ActiveRecord, or you'd prefer not to run each of your 45 | # examples within a transaction, remove the following line or assign false 46 | # instead of true. 47 | config.use_transactional_fixtures = false 48 | 49 | config.before(:each) do 50 | DatabaseCleaner.strategy = :transaction 51 | end 52 | 53 | config.before(:each, js: true) do 54 | DatabaseCleaner.strategy = :truncation 55 | end 56 | 57 | config.before(:each) do 58 | DatabaseCleaner.start 59 | end 60 | 61 | config.after(:each) do 62 | DatabaseCleaner.clean 63 | end 64 | 65 | config.infer_spec_type_from_file_location! 66 | 67 | config.include Devise::TestHelpers, type: :controller 68 | config.include WaitForAjax, type: :feature 69 | end 70 | -------------------------------------------------------------------------------- /spec/spec_helper.rb: -------------------------------------------------------------------------------- 1 | RSpec.configure do |config| 2 | # These two settings work together to allow you to limit a spec run 3 | # to individual examples or groups you care about by tagging them with 4 | # `:focus` metadata. When nothing is tagged with `:focus`, all examples 5 | # get run. 6 | config.filter_run :focus 7 | config.run_all_when_everything_filtered = true 8 | 9 | # Many RSpec users commonly either run the entire suite or an individual 10 | # file, and it's useful to allow more verbose output when running an 11 | # individual spec file. 12 | if config.files_to_run.one? 13 | # Use the documentation formatter for detailed output, 14 | # unless a formatter has already been configured 15 | # (e.g. via a command-line flag). 16 | config.default_formatter = 'doc' 17 | end 18 | 19 | # Print the 10 slowest examples and example groups at the 20 | # end of the spec run, to help surface which specs are running 21 | # particularly slow. 22 | config.profile_examples = 10 23 | 24 | # Run specs in random order to surface order dependencies. If you find an 25 | # order dependency and want to debug it, you can fix the order by providing 26 | # the seed, which is printed after each run. 27 | # --seed 1234 28 | config.order = :random 29 | 30 | # Seed global randomization in this process using the `--seed` CLI option. 31 | # Setting this allows you to use `--seed` to deterministically reproduce 32 | # test failures related to randomization by passing the same `--seed` value 33 | # as the one that triggered the failure. 34 | Kernel.srand config.seed 35 | 36 | # rspec-expectations config goes here. You can use an alternate 37 | # assertion/expectation library such as wrong or the stdlib/minitest 38 | # assertions if you prefer. 39 | config.expect_with :rspec do |expectations| 40 | # Enable only the newer, non-monkey-patching expect syntax. 41 | # For more details, see: 42 | # - http://myronmars.to/n/dev-blog/2012/06/rspecs-new-expectation-syntax 43 | expectations.syntax = :expect 44 | end 45 | 46 | # rspec-mocks config goes here. You can use an alternate test double 47 | # library (such as bogus or mocha) by changing the `mock_with` option here. 48 | config.mock_with :rspec do |mocks| 49 | # Enable only the newer, non-monkey-patching expect syntax. 50 | # For more details, see: 51 | # - http://teaisaweso.me/blog/2013/05/27/rspecs-new-message-expectation-syntax/ 52 | mocks.syntax = :expect 53 | 54 | # Prevents you from mocking or stubbing a method that does not exist on 55 | # a real object. This is generally recommended. 56 | mocks.verify_partial_doubles = true 57 | end 58 | end 59 | -------------------------------------------------------------------------------- /spec/support/wait_for_ajax.rb: -------------------------------------------------------------------------------- 1 | module WaitForAjax 2 | def wait_for_ajax(count = 1) 3 | page.execute_script 'window._ajaxCalls = 0, window._ajaxCompleteCounter = function() { window._ajaxCalls += 1; }' 4 | page.execute_script '$(document).on("ajaxComplete", window._ajaxCompleteCounter)' 5 | 6 | yield 7 | 8 | Timeout.timeout(Capybara.default_max_wait_time) do 9 | loop until finished_all_ajax_requests?(count) 10 | end 11 | 12 | page.execute_script '$(document).off("ajaxComplete", window._ajaxCompleteCounter)' 13 | page.execute_script 'delete window._ajaxCompleteCounter, window._ajaxCalls' 14 | end 15 | 16 | def finished_all_ajax_requests?(count) 17 | page.evaluate_script('window._ajaxCalls') == count 18 | end 19 | end 20 | -------------------------------------------------------------------------------- /vendor/assets/javascripts/jquery.mjs.nestedSortable.js: -------------------------------------------------------------------------------- 1 | /* 2 | * jQuery UI Nested Sortable 3 | * v 2.0 / 29 oct 2012 4 | * http://mjsarfatti.com/sandbox/nestedSortable 5 | * 6 | * Depends on: 7 | * jquery.ui.sortable.js 1.10+ 8 | * 9 | * Copyright (c) 2010-2013 Manuele J Sarfatti 10 | * Licensed under the MIT License 11 | * http://www.opensource.org/licenses/mit-license.php 12 | */ 13 | 14 | (function($) { 15 | 16 | function isOverAxis( x, reference, size ) { 17 | return ( x > reference ) && ( x < ( reference + size ) ); 18 | } 19 | 20 | $.widget("mjs.nestedSortable", $.extend({}, $.ui.sortable.prototype, { 21 | 22 | options: { 23 | doNotClear: false, 24 | expandOnHover: 700, 25 | isAllowed: function(placeholder, placeholderParent, originalItem) { return true; }, 26 | isTree: false, 27 | listType: 'ol', 28 | maxLevels: 0, 29 | protectRoot: false, 30 | rootID: null, 31 | rtl: false, 32 | startCollapsed: false, 33 | tabSize: 20, 34 | 35 | branchClass: 'mjs-nestedSortable-branch', 36 | collapsedClass: 'mjs-nestedSortable-collapsed', 37 | disableNestingClass: 'mjs-nestedSortable-no-nesting', 38 | errorClass: 'mjs-nestedSortable-error', 39 | expandedClass: 'mjs-nestedSortable-expanded', 40 | hoveringClass: 'mjs-nestedSortable-hovering', 41 | leafClass: 'mjs-nestedSortable-leaf' 42 | }, 43 | 44 | _create: function() { 45 | this.element.data('ui-sortable', this.element.data('mjs-nestedSortable')); 46 | 47 | // mjs - prevent browser from freezing if the HTML is not correct 48 | if (!this.element.is(this.options.listType)) 49 | throw new Error('nestedSortable: Please check that the listType option is set to your actual list type'); 50 | 51 | // mjs - force 'intersect' tolerance method if we have a tree with expanding/collapsing functionality 52 | if (this.options.isTree && this.options.expandOnHover) { 53 | this.options.tolerance = 'intersect'; 54 | } 55 | 56 | $.ui.sortable.prototype._create.apply(this, arguments); 57 | 58 | // mjs - prepare the tree by applying the right classes (the CSS is responsible for actual hide/show functionality) 59 | if (this.options.isTree) { 60 | var self = this; 61 | $(this.items).each(function() { 62 | var $li = this.item; 63 | if ($li.children(self.options.listType).length) { 64 | $li.addClass(self.options.branchClass); 65 | // expand/collapse class only if they have children 66 | if (self.options.startCollapsed) $li.addClass(self.options.collapsedClass); 67 | else $li.addClass(self.options.expandedClass); 68 | } else { 69 | $li.addClass(self.options.leafClass); 70 | } 71 | }) 72 | } 73 | }, 74 | 75 | _destroy: function() { 76 | this.element 77 | .removeData("mjs-nestedSortable") 78 | .removeData("ui-sortable"); 79 | return $.ui.sortable.prototype._destroy.apply(this, arguments); 80 | }, 81 | 82 | _mouseDrag: function(event) { 83 | var i, item, itemElement, intersection, 84 | o = this.options, 85 | scrolled = false; 86 | 87 | //Compute the helpers position 88 | this.position = this._generatePosition(event); 89 | this.positionAbs = this._convertPositionTo("absolute"); 90 | 91 | if (!this.lastPositionAbs) { 92 | this.lastPositionAbs = this.positionAbs; 93 | } 94 | 95 | //Do scrolling 96 | if(this.options.scroll) { 97 | if(this.scrollParent[0] != document && this.scrollParent[0].tagName != 'HTML') { 98 | 99 | if((this.overflowOffset.top + this.scrollParent[0].offsetHeight) - event.pageY < o.scrollSensitivity) { 100 | this.scrollParent[0].scrollTop = scrolled = this.scrollParent[0].scrollTop + o.scrollSpeed; 101 | } else if(event.pageY - this.overflowOffset.top < o.scrollSensitivity) { 102 | this.scrollParent[0].scrollTop = scrolled = this.scrollParent[0].scrollTop - o.scrollSpeed; 103 | } 104 | 105 | if((this.overflowOffset.left + this.scrollParent[0].offsetWidth) - event.pageX < o.scrollSensitivity) { 106 | this.scrollParent[0].scrollLeft = scrolled = this.scrollParent[0].scrollLeft + o.scrollSpeed; 107 | } else if(event.pageX - this.overflowOffset.left < o.scrollSensitivity) { 108 | this.scrollParent[0].scrollLeft = scrolled = this.scrollParent[0].scrollLeft - o.scrollSpeed; 109 | } 110 | 111 | } else { 112 | 113 | if(event.pageY - $(document).scrollTop() < o.scrollSensitivity) { 114 | scrolled = $(document).scrollTop($(document).scrollTop() - o.scrollSpeed); 115 | } else if($(window).height() - (event.pageY - $(document).scrollTop()) < o.scrollSensitivity) { 116 | scrolled = $(document).scrollTop($(document).scrollTop() + o.scrollSpeed); 117 | } 118 | 119 | if(event.pageX - $(document).scrollLeft() < o.scrollSensitivity) { 120 | scrolled = $(document).scrollLeft($(document).scrollLeft() - o.scrollSpeed); 121 | } else if($(window).width() - (event.pageX - $(document).scrollLeft()) < o.scrollSensitivity) { 122 | scrolled = $(document).scrollLeft($(document).scrollLeft() + o.scrollSpeed); 123 | } 124 | 125 | } 126 | 127 | if(scrolled !== false && $.ui.ddmanager && !o.dropBehaviour) 128 | $.ui.ddmanager.prepareOffsets(this, event); 129 | } 130 | 131 | //Regenerate the absolute position used for position checks 132 | this.positionAbs = this._convertPositionTo("absolute"); 133 | 134 | // mjs - find the top offset before rearrangement, 135 | var previousTopOffset = this.placeholder.offset().top; 136 | 137 | //Set the helper position 138 | if(!this.options.axis || this.options.axis !== "y") { 139 | this.helper[0].style.left = this.position.left+"px"; 140 | } 141 | if(!this.options.axis || this.options.axis !== "x") { 142 | this.helper[0].style.top = this.position.top+"px"; 143 | } 144 | 145 | // mjs - check and reset hovering state at each cycle 146 | this.hovering = this.hovering ? this.hovering : null; 147 | this.mouseentered = this.mouseentered ? this.mouseentered : false; 148 | 149 | // mjs - let's start caching some variables 150 | var parentItem = (this.placeholder[0].parentNode.parentNode && 151 | $(this.placeholder[0].parentNode.parentNode).closest('.ui-sortable').length) 152 | ? $(this.placeholder[0].parentNode.parentNode) 153 | : null, 154 | level = this._getLevel(this.placeholder), 155 | childLevels = this._getChildLevels(this.helper); 156 | 157 | var newList = document.createElement(o.listType); 158 | 159 | //Rearrange 160 | for (i = this.items.length - 1; i >= 0; i--) { 161 | 162 | //Cache variables and intersection, continue if no intersection 163 | item = this.items[i]; 164 | itemElement = item.item[0]; 165 | intersection = this._intersectsWithPointer(item); 166 | if (!intersection) { 167 | continue; 168 | } 169 | 170 | // Only put the placeholder inside the current Container, skip all 171 | // items form other containers. This works because when moving 172 | // an item from one container to another the 173 | // currentContainer is switched before the placeholder is moved. 174 | // 175 | // Without this moving items in "sub-sortables" can cause the placeholder to jitter 176 | // beetween the outer and inner container. 177 | if (item.instance !== this.currentContainer) { 178 | continue; 179 | } 180 | 181 | // cannot intersect with itself 182 | // no useless actions that have been done before 183 | // no action if the item moved is the parent of the item checked 184 | if (itemElement !== this.currentItem[0] && 185 | this.placeholder[intersection === 1 ? "next" : "prev"]()[0] !== itemElement && 186 | !$.contains(this.placeholder[0], itemElement) && 187 | (this.options.type === "semi-dynamic" ? !$.contains(this.element[0], itemElement) : true) 188 | ) { 189 | 190 | // mjs - we are intersecting an element: trigger the mouseenter event and store this state 191 | if (!this.mouseentered) { 192 | $(itemElement).mouseenter(); 193 | this.mouseentered = true; 194 | } 195 | 196 | // mjs - if the element has children and they are hidden, show them after a delay (CSS responsible) 197 | if (o.isTree && $(itemElement).hasClass(o.collapsedClass) && o.expandOnHover) { 198 | if (!this.hovering) { 199 | $(itemElement).addClass(o.hoveringClass); 200 | var self = this; 201 | this.hovering = window.setTimeout(function() { 202 | $(itemElement).removeClass(o.collapsedClass).addClass(o.expandedClass); 203 | self.refreshPositions(); 204 | self._trigger("expand", event, self._uiHash()); 205 | }, o.expandOnHover); 206 | } 207 | } 208 | 209 | this.direction = intersection == 1 ? "down" : "up"; 210 | 211 | // mjs - rearrange the elements and reset timeouts and hovering state 212 | if (this.options.tolerance == "pointer" || this._intersectsWithSides(item)) { 213 | $(itemElement).mouseleave(); 214 | this.mouseentered = false; 215 | $(itemElement).removeClass(o.hoveringClass); 216 | this.hovering && window.clearTimeout(this.hovering); 217 | this.hovering = null; 218 | 219 | // mjs - do not switch container if it's a root item and 'protectRoot' is true 220 | // or if it's not a root item but we are trying to make it root 221 | if (o.protectRoot 222 | && ! (this.currentItem[0].parentNode == this.element[0] // it's a root item 223 | && itemElement.parentNode != this.element[0]) // it's intersecting a non-root item 224 | ) { 225 | if (this.currentItem[0].parentNode != this.element[0] 226 | && itemElement.parentNode == this.element[0] 227 | ) { 228 | 229 | if ( ! $(itemElement).children(o.listType).length) { 230 | itemElement.appendChild(newList); 231 | o.isTree && $(itemElement).removeClass(o.leafClass).addClass(o.branchClass + ' ' + o.expandedClass); 232 | } 233 | 234 | var a = this.direction === "down" ? $(itemElement).prev().children(o.listType) : $(itemElement).children(o.listType); 235 | if (a[0] !== undefined) { 236 | this._rearrange(event, null, a); 237 | } 238 | 239 | } else { 240 | this._rearrange(event, item); 241 | } 242 | } else if ( ! o.protectRoot) { 243 | this._rearrange(event, item); 244 | } 245 | } else { 246 | break; 247 | } 248 | 249 | // Clear emtpy ul's/ol's 250 | this._clearEmpty(itemElement); 251 | 252 | this._trigger("change", event, this._uiHash()); 253 | break; 254 | } 255 | } 256 | 257 | // mjs - to find the previous sibling in the list, keep backtracking until we hit a valid list item. 258 | var previousItem = this.placeholder[0].previousSibling ? $(this.placeholder[0].previousSibling) : null; 259 | if (previousItem != null) { 260 | while (previousItem[0].nodeName.toLowerCase() != 'li' || previousItem[0] == this.currentItem[0] || previousItem[0] == this.helper[0]) { 261 | if (previousItem[0].previousSibling) { 262 | previousItem = $(previousItem[0].previousSibling); 263 | } else { 264 | previousItem = null; 265 | break; 266 | } 267 | } 268 | } 269 | 270 | // mjs - to find the next sibling in the list, keep stepping forward until we hit a valid list item. 271 | var nextItem = this.placeholder[0].nextSibling ? $(this.placeholder[0].nextSibling) : null; 272 | if (nextItem != null) { 273 | while (nextItem[0].nodeName.toLowerCase() != 'li' || nextItem[0] == this.currentItem[0] || nextItem[0] == this.helper[0]) { 274 | if (nextItem[0].nextSibling) { 275 | nextItem = $(nextItem[0].nextSibling); 276 | } else { 277 | nextItem = null; 278 | break; 279 | } 280 | } 281 | } 282 | 283 | this.beyondMaxLevels = 0; 284 | 285 | // mjs - if the item is moved to the left, send it one level up but only if it's at the bottom of the list 286 | if (parentItem != null 287 | && nextItem == null 288 | && ! (o.protectRoot && parentItem[0].parentNode == this.element[0]) 289 | && 290 | (o.rtl && (this.positionAbs.left + this.helper.outerWidth() > parentItem.offset().left + parentItem.outerWidth()) 291 | || ! o.rtl && (this.positionAbs.left < parentItem.offset().left)) 292 | ) { 293 | 294 | parentItem.after(this.placeholder[0]); 295 | if (o.isTree && parentItem.children(o.listItem).children('li:visible:not(.ui-sortable-helper)').length < 1) { 296 | parentItem.removeClass(this.options.branchClass + ' ' + this.options.expandedClass) 297 | .addClass(this.options.leafClass); 298 | } 299 | this._clearEmpty(parentItem[0]); 300 | this._trigger("change", event, this._uiHash()); 301 | } 302 | // mjs - if the item is below a sibling and is moved to the right, make it a child of that sibling 303 | else if (previousItem != null 304 | && ! previousItem.hasClass(o.disableNestingClass) 305 | && 306 | (previousItem.children(o.listType).length && previousItem.children(o.listType).is(':visible') 307 | || ! previousItem.children(o.listType).length) 308 | && ! (o.protectRoot && this.currentItem[0].parentNode == this.element[0]) 309 | && 310 | (o.rtl && (this.positionAbs.left + this.helper.outerWidth() < previousItem.offset().left + previousItem.outerWidth() - o.tabSize) 311 | || ! o.rtl && (this.positionAbs.left > previousItem.offset().left + o.tabSize)) 312 | ) { 313 | 314 | this._isAllowed(previousItem, level, level+childLevels+1); 315 | 316 | if (!previousItem.children(o.listType).length) { 317 | previousItem[0].appendChild(newList); 318 | o.isTree && previousItem.removeClass(o.leafClass).addClass(o.branchClass + ' ' + o.expandedClass); 319 | } 320 | 321 | // mjs - if this item is being moved from the top, add it to the top of the list. 322 | if (previousTopOffset && (previousTopOffset <= previousItem.offset().top)) { 323 | previousItem.children(o.listType).prepend(this.placeholder); 324 | } 325 | // mjs - otherwise, add it to the bottom of the list. 326 | else { 327 | previousItem.children(o.listType)[0].appendChild(this.placeholder[0]); 328 | } 329 | 330 | this._trigger("change", event, this._uiHash()); 331 | } 332 | else { 333 | this._isAllowed(parentItem, level, level+childLevels); 334 | } 335 | 336 | //Post events to containers 337 | this._contactContainers(event); 338 | 339 | //Interconnect with droppables 340 | if($.ui.ddmanager) { 341 | $.ui.ddmanager.drag(this, event); 342 | } 343 | 344 | //Call callbacks 345 | this._trigger('sort', event, this._uiHash()); 346 | 347 | this.lastPositionAbs = this.positionAbs; 348 | return false; 349 | 350 | }, 351 | 352 | _mouseStop: function(event, noPropagation) { 353 | 354 | // mjs - if the item is in a position not allowed, send it back 355 | if (this.beyondMaxLevels) { 356 | 357 | this.placeholder.removeClass(this.options.errorClass); 358 | 359 | if (this.domPosition.prev) { 360 | $(this.domPosition.prev).after(this.placeholder); 361 | } else { 362 | $(this.domPosition.parent).prepend(this.placeholder); 363 | } 364 | 365 | this._trigger("revert", event, this._uiHash()); 366 | 367 | } 368 | 369 | 370 | // mjs - clear the hovering timeout, just to be sure 371 | $('.'+this.options.hoveringClass).mouseleave().removeClass(this.options.hoveringClass); 372 | this.mouseentered = false; 373 | this.hovering && window.clearTimeout(this.hovering); 374 | this.hovering = null; 375 | 376 | $.ui.sortable.prototype._mouseStop.apply(this, arguments); 377 | 378 | }, 379 | 380 | // mjs - this function is slightly modified to make it easier to hover over a collapsed element and have it expand 381 | _intersectsWithSides: function(item) { 382 | 383 | var half = this.options.isTree ? .8 : .5; 384 | 385 | var isOverBottomHalf = isOverAxis(this.positionAbs.top + this.offset.click.top, item.top + (item.height*half), item.height), 386 | isOverTopHalf = isOverAxis(this.positionAbs.top + this.offset.click.top, item.top - (item.height*half), item.height), 387 | isOverRightHalf = isOverAxis(this.positionAbs.left + this.offset.click.left, item.left + (item.width/2), item.width), 388 | verticalDirection = this._getDragVerticalDirection(), 389 | horizontalDirection = this._getDragHorizontalDirection(); 390 | 391 | if (this.floating && horizontalDirection) { 392 | return ((horizontalDirection == "right" && isOverRightHalf) || (horizontalDirection == "left" && !isOverRightHalf)); 393 | } else { 394 | return verticalDirection && ((verticalDirection == "down" && isOverBottomHalf) || (verticalDirection == "up" && isOverTopHalf)); 395 | } 396 | 397 | }, 398 | 399 | _contactContainers: function(event) { 400 | 401 | if (this.options.protectRoot && this.currentItem[0].parentNode == this.element[0] ) { 402 | return; 403 | } 404 | 405 | $.ui.sortable.prototype._contactContainers.apply(this, arguments); 406 | 407 | }, 408 | 409 | _clear: function(event, noPropagation) { 410 | 411 | $.ui.sortable.prototype._clear.apply(this, arguments); 412 | 413 | // mjs - clean last empty ul/ol 414 | for (var i = this.items.length - 1; i >= 0; i--) { 415 | var item = this.items[i].item[0]; 416 | this._clearEmpty(item); 417 | } 418 | 419 | }, 420 | 421 | serialize: function(options) { 422 | 423 | var o = $.extend({}, this.options, options), 424 | items = this._getItemsAsjQuery(o && o.connected), 425 | str = []; 426 | 427 | $(items).each(function() { 428 | var res = ($(o.item || this).attr(o.attribute || 'id') || '') 429 | .match(o.expression || (/(.+)[=_](.+)/)), 430 | pid = ($(o.item || this).parent(o.listType) 431 | .parent(o.items) 432 | .attr(o.attribute || 'id') || '') 433 | .match(o.expression || (/(.+)[=_](.+)/)); 434 | 435 | if (res) { 436 | str.push(((o.key || res[1]) + '[' + (o.key && o.expression ? res[1] : res[2]) + ']') 437 | + '=' 438 | + (pid ? (o.key && o.expression ? pid[1] : pid[2]) : o.rootID)); 439 | } 440 | }); 441 | 442 | if(!str.length && o.key) { 443 | str.push(o.key + '='); 444 | } 445 | 446 | return str.join('&'); 447 | 448 | }, 449 | 450 | toHierarchy: function(options) { 451 | 452 | var o = $.extend({}, this.options, options), 453 | sDepth = o.startDepthCount || 0, 454 | ret = []; 455 | 456 | $(this.element).children(o.items).each(function () { 457 | var level = _recursiveItems(this); 458 | ret.push(level); 459 | }); 460 | 461 | return ret; 462 | 463 | function _recursiveItems(item) { 464 | var id = ($(item).attr(o.attribute || 'id') || '').match(o.expression || (/(.+)[-=_](.+)/)); 465 | if (id) { 466 | var currentItem = {"id" : id[2]}; 467 | if ($(item).children(o.listType).children(o.items).length > 0) { 468 | currentItem.children = []; 469 | $(item).children(o.listType).children(o.items).each(function() { 470 | var level = _recursiveItems(this); 471 | currentItem.children.push(level); 472 | }); 473 | } 474 | return currentItem; 475 | } 476 | } 477 | }, 478 | 479 | toArray: function(options) { 480 | 481 | var o = $.extend({}, this.options, options), 482 | sDepth = o.startDepthCount || 0, 483 | ret = [], 484 | left = 1; 485 | 486 | if (!o.excludeRoot) { 487 | ret.push({ 488 | "item_id": o.rootID, 489 | "parent_id": null, 490 | "depth": sDepth, 491 | "left": left, 492 | "right": ($(o.items, this.element).length + 1) * 2 493 | }); 494 | left++ 495 | } 496 | 497 | $(this.element).children(o.items).each(function () { 498 | left = _recursiveArray(this, sDepth + 1, left); 499 | }); 500 | 501 | ret = ret.sort(function(a,b){ return (a.left - b.left); }); 502 | 503 | return ret; 504 | 505 | function _recursiveArray(item, depth, left) { 506 | 507 | var right = left + 1, 508 | id, 509 | pid; 510 | 511 | if ($(item).children(o.listType).children(o.items).length > 0) { 512 | depth ++; 513 | $(item).children(o.listType).children(o.items).each(function () { 514 | right = _recursiveArray($(this), depth, right); 515 | }); 516 | depth --; 517 | } 518 | 519 | id = ($(item).attr(o.attribute || 'id')).match(o.expression || (/(.+)[-=_](.+)/)); 520 | 521 | if (depth === sDepth + 1) { 522 | pid = o.rootID; 523 | } else { 524 | var parentItem = ($(item).parent(o.listType) 525 | .parent(o.items) 526 | .attr(o.attribute || 'id')) 527 | .match(o.expression || (/(.+)[-=_](.+)/)); 528 | pid = parentItem[2]; 529 | } 530 | 531 | if (id) { 532 | ret.push({"item_id": id[2], "parent_id": pid, "depth": depth, "left": left, "right": right}); 533 | } 534 | 535 | left = right + 1; 536 | return left; 537 | } 538 | 539 | }, 540 | 541 | _clearEmpty: function(item) { 542 | var o = this.options; 543 | 544 | var emptyList = $(item).children(o.listType); 545 | 546 | if (emptyList.length && !emptyList.children().length && !o.doNotClear) { 547 | o.isTree && $(item).removeClass(o.branchClass + ' ' + o.expandedClass).addClass(o.leafClass); 548 | emptyList.remove(); 549 | } else if (o.isTree && emptyList.length && emptyList.children().length && emptyList.is(':visible')) { 550 | $(item).removeClass(o.leafClass).addClass(o.branchClass + ' ' + o.expandedClass); 551 | } else if (o.isTree && emptyList.length && emptyList.children().length && !emptyList.is(':visible')) { 552 | $(item).removeClass(o.leafClass).addClass(o.branchClass + ' ' + o.collapsedClass); 553 | } 554 | 555 | }, 556 | 557 | _getLevel: function(item) { 558 | 559 | var level = 1; 560 | 561 | if (this.options.listType) { 562 | var list = item.closest(this.options.listType); 563 | while (list && list.length > 0 && 564 | !list.is('.ui-sortable')) { 565 | level++; 566 | list = list.parent().closest(this.options.listType); 567 | } 568 | } 569 | 570 | return level; 571 | }, 572 | 573 | _getChildLevels: function(parent, depth) { 574 | var self = this, 575 | o = this.options, 576 | result = 0; 577 | depth = depth || 0; 578 | 579 | $(parent).children(o.listType).children(o.items).each(function (index, child) { 580 | result = Math.max(self._getChildLevels(child, depth + 1), result); 581 | }); 582 | 583 | return depth ? result + 1 : result; 584 | }, 585 | 586 | _isAllowed: function(parentItem, level, levels) { 587 | var o = this.options, 588 | maxLevels = this.placeholder.closest('.ui-sortable').nestedSortable('option', 'maxLevels'); // this takes into account the maxLevels set to the recipient list 589 | 590 | // mjs - is the root protected? 591 | // mjs - are we nesting too deep? 592 | if ( ! o.isAllowed(this.placeholder, parentItem, this.currentItem)) { 593 | this.placeholder.addClass(o.errorClass); 594 | if (maxLevels < levels && maxLevels != 0) { 595 | this.beyondMaxLevels = levels - maxLevels; 596 | } else { 597 | this.beyondMaxLevels = 1; 598 | } 599 | } else { 600 | if (maxLevels < levels && maxLevels != 0) { 601 | this.placeholder.addClass(o.errorClass); 602 | this.beyondMaxLevels = levels - maxLevels; 603 | } else { 604 | this.placeholder.removeClass(o.errorClass); 605 | this.beyondMaxLevels = 0; 606 | } 607 | } 608 | } 609 | 610 | })); 611 | 612 | $.mjs.nestedSortable.prototype.options = $.extend({}, $.ui.sortable.prototype.options, $.mjs.nestedSortable.prototype.options); 613 | })(jQuery); 614 | --------------------------------------------------------------------------------