Repository: itmammoth/rails_sortable
Branch: master
Commit: 31f49365a545
Files: 98
Total size: 58.2 KB
Directory structure:
gitextract_pf92r3a1/
├── .envrc
├── .gitignore
├── Gemfile
├── LICENSE
├── README.md
├── Rakefile
├── SECURITY.md
├── app/
│ ├── controllers/
│ │ ├── .keep
│ │ └── sortable_controller.rb
│ └── models/
│ ├── .keep
│ └── rails_sortable/
│ └── model.rb
├── bin/
│ ├── bundle
│ ├── coderay
│ ├── htmldiff
│ ├── ldiff
│ ├── nokogiri
│ ├── pry
│ ├── rackup
│ ├── rails
│ ├── rake
│ ├── rspec
│ ├── sprockets
│ └── thor
├── config/
│ └── routes.rb
├── lib/
│ ├── rails_sortable/
│ │ ├── core_ext/
│ │ │ └── enumerable.rb
│ │ ├── core_ext.rb
│ │ ├── engine.rb
│ │ └── version.rb
│ └── rails_sortable.rb
├── rails_sortable.gemspec
├── spec/
│ ├── controllers/
│ │ └── sortable_controller_spec.rb
│ ├── dummy/
│ │ ├── README.rdoc
│ │ ├── Rakefile
│ │ ├── app/
│ │ │ ├── assets/
│ │ │ │ ├── config/
│ │ │ │ │ └── manifest.js
│ │ │ │ ├── images/
│ │ │ │ │ └── .keep
│ │ │ │ ├── javascripts/
│ │ │ │ │ ├── application.js
│ │ │ │ │ ├── items.js
│ │ │ │ │ ├── multiple_classes.js
│ │ │ │ │ └── sequenced_items.js
│ │ │ │ └── stylesheets/
│ │ │ │ ├── application.css
│ │ │ │ └── scaffold.css
│ │ │ ├── controllers/
│ │ │ │ ├── application_controller.rb
│ │ │ │ ├── concerns/
│ │ │ │ │ └── .keep
│ │ │ │ ├── items_controller.rb
│ │ │ │ ├── multiple_classes_controller.rb
│ │ │ │ └── sequenced_items_controller.rb
│ │ │ ├── models/
│ │ │ │ ├── .keep
│ │ │ │ ├── concerns/
│ │ │ │ │ └── .keep
│ │ │ │ ├── first_item.rb
│ │ │ │ ├── item.rb
│ │ │ │ ├── second_item.rb
│ │ │ │ ├── sequenced_item.rb
│ │ │ │ └── validated_item.rb
│ │ │ └── views/
│ │ │ ├── items/
│ │ │ │ ├── _form.html.erb
│ │ │ │ ├── edit.html.erb
│ │ │ │ ├── index.html.erb
│ │ │ │ ├── new.html.erb
│ │ │ │ └── show.html.erb
│ │ │ ├── layouts/
│ │ │ │ └── application.html.erb
│ │ │ ├── multiple_classes/
│ │ │ │ └── index.html.erb
│ │ │ └── sequenced_items/
│ │ │ ├── _form.html.erb
│ │ │ ├── edit.html.erb
│ │ │ ├── index.html.erb
│ │ │ ├── new.html.erb
│ │ │ └── show.html.erb
│ │ ├── bin/
│ │ │ ├── bundle
│ │ │ ├── rails
│ │ │ └── rake
│ │ ├── config/
│ │ │ ├── application.rb
│ │ │ ├── boot.rb
│ │ │ ├── database.yml
│ │ │ ├── environment.rb
│ │ │ ├── environments/
│ │ │ │ ├── development.rb
│ │ │ │ ├── production.rb
│ │ │ │ └── test.rb
│ │ │ ├── initializers/
│ │ │ │ ├── backtrace_silencers.rb
│ │ │ │ ├── filter_parameter_logging.rb
│ │ │ │ ├── inflections.rb
│ │ │ │ ├── mime_types.rb
│ │ │ │ ├── secret_token.rb
│ │ │ │ ├── session_store.rb
│ │ │ │ └── wrap_parameters.rb
│ │ │ ├── locales/
│ │ │ │ └── en.yml
│ │ │ └── routes.rb
│ │ ├── config.ru
│ │ ├── db/
│ │ │ ├── migrate/
│ │ │ │ ├── 20131223124841_create_items.rb
│ │ │ │ ├── 20170414031946_create_sequenced_items.rb
│ │ │ │ └── 20180427061457_create_multiple_classes.rb
│ │ │ └── seeds.rb
│ │ ├── lib/
│ │ │ └── assets/
│ │ │ └── .keep
│ │ ├── log/
│ │ │ └── .keep
│ │ └── public/
│ │ ├── 404.html
│ │ ├── 422.html
│ │ └── 500.html
│ ├── models/
│ │ └── rails_sortable/
│ │ └── model_spec.rb
│ └── spec_helper.rb
└── vendor/
└── assets/
└── javascripts/
├── plugin.js
└── rails_sortable.js
================================================
FILE CONTENTS
================================================
================================================
FILE: .envrc
================================================
export PATH=$PWD/bin:$PATH
================================================
FILE: .gitignore
================================================
.bundle/
log/*.log
pkg/
spec/dummy/db/*.sqlite3
spec/dummy/db/*.sqlite3-journal
spec/dummy/db/schema.rb
spec/dummy/log/*.log
spec/dummy/tmp/
spec/dummy/.sass-cache
vendor/bundle
Gemfile.lock
gemfiles/*.lock
.rspec
*.gem
.tags
.ruby-version
.idea
================================================
FILE: Gemfile
================================================
source "https://rubygems.org"
# Declare your gem's dependencies in rails_sortable.gemspec.
# Bundler will treat runtime dependencies like base dependencies, and
# development dependencies will be added by default to the :development group.
gemspec
# Declare any dependencies that are still in development here instead of in
# your gemspec. These might include edge Rails or gems from your path or
# Git. Remember to move these dependencies to your gemspec before releasing
# your gem to rubygems.org.
# To use debugger
# gem 'debugger'
================================================
FILE: LICENSE
================================================
Copyright 2013 itmammoth
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
================================================
FILE: README.md
================================================
# RailsSortable
[](https://travis-ci.org/itmammoth/rails_sortable)
RailsSortable is a simple Rails gem that allows you to create a listing view with drag & drop sorting. The arranged order will be persisted in the table without any pain.

# Setup
Add the following to your `Gemfile` then run bundle to install them.
```
gem 'jquery-rails'
gem 'jquery-ui-rails'
gem 'rails_sortable'
```
And then add the following to the asset pipeline in the `application.js`:
```
//= require jquery
//= require jquery_ujs
//= require jquery-ui/widgets/sortable
//= require rails_sortable
```
# Usage
RailsSortable requires a specific column on the ActiveRecord Model for its implementation.
For instance, the following migration indicates the case that you are attempting to make `Item` model sortable.
```ruby
class CreateItems < ActiveRecord::Migration[5.1]
def change
create_table :items do |t|
t.string :title
t.integer :sort # for RailsSortable
t.timestamps
end
end
end
```
and `Item` model as
```ruby
class Item < ApplicationRecord
include RailsSortable::Model
set_sortable :sort # Indicate a sort column
# without_updating_timestamps: true, # If you do NOT want timestamps to be updated on sorting
# without_validations: true # If you do NOT want validations to be run on sorting
end
```
and `ItemsController` as
```ruby
class ItemsController < ApplicationController
def index
@items = Item.order(:sort).all
end
end
```
and the listing view (typically - index.html.erb) as
```erb
...
<% @items.each_with_sortable_id do |item, sortable_id| %>
| <%= item.title %> |
<%= item.sort %> |
<%= link_to 'Show', item %> |
<%= link_to 'Edit', edit_item_path(item) %> |
<%= link_to 'Destroy', item, method: :delete, data: { confirm: 'Are you sure?' } %> |
<% end %>
...
<% @items.each do |item| %>
...
```
finally, apply sortable with Javascript.
```javascript
$(function() {
$('.sortable').railsSortable();
});
```
## More
Please have a look at [Use cases@wiki](https://github.com/itmammoth/rails_sortable/wiki#use-cases) for further information.
# Javascript options
jQuery plugin `railsSortable` is just a wrapper of `jquery.ui.sortable`. therefore it accepts all of `sortable` options.
see the [http://api.jqueryui.com/sortable/](http://api.jqueryui.com/sortable/) to get the details.
# Contribution
Fork it, then install required gems like below.
```bash
$ bundle install
```
Please give me a PR freely.
### Testing
```bash
# Test with a dummy application
$ spec/dummy/bin/rails db:migrate
$ spec/dummy/bin/rails s
# Insert test data
$ RAILS_ENV=test spec/dummy/bin/rails db:migrate
$ spec/dummy/bin/rails db:seed
# Run specs
$ bundle exec rspec
```
# Licence
MIT Licence.
================================================
FILE: Rakefile
================================================
begin
require 'bundler/setup'
rescue LoadError
puts 'You must `gem install bundler` and `bundle install` to run rake tasks'
end
require 'rdoc/task'
RDoc::Task.new(:rdoc) do |rdoc|
rdoc.rdoc_dir = 'rdoc'
rdoc.title = 'RailsSortable'
rdoc.options << '--line-numbers'
rdoc.rdoc_files.include('README.rdoc')
rdoc.rdoc_files.include('lib/**/*.rb')
end
APP_RAKEFILE = File.expand_path("../spec/dummy/Rakefile", __FILE__)
load 'rails/tasks/engine.rake'
Bundler::GemHelper.install_tasks
================================================
FILE: SECURITY.md
================================================
# Security Policy
## Supported Versions
Use this section to tell people about which versions of your project are
currently being supported with security updates.
| Version | Supported |
| ------- | ------------------ |
| 5.1.x | :white_check_mark: |
| 5.0.x | :x: |
| 4.0.x | :white_check_mark: |
| < 4.0 | :x: |
## Reporting a Vulnerability
Use this section to tell people how to report a vulnerability.
Tell them where to go, how often they can expect to get an update on a
reported vulnerability, what to expect if the vulnerability is accepted or
declined, etc.
================================================
FILE: app/controllers/.keep
================================================
================================================
FILE: app/controllers/sortable_controller.rb
================================================
class SortableController < ApplicationController
VERIFIER = Rails.application.message_verifier(:rails_sortable_generate_sortable_id)
#
# post /sortable/reorder, rails_sortable: [
# "BAhJIhVjbGFzcz1JdGVtLGlkPTUwBjoGRVQ=--b48adfad6d6d7764e4106c44fc090fcad15d721e",
# "BAhJIhVjbGFzcz1JdGVtLGlkPTQxBjoGRVQ=--ac1c2d3b8eae8dd72e49fae302005e5ae4fc00a4", ...]
# Param `rails_sorable` is an array object containing encoded tokens,
# and each token must be able to be decoded with VERIFIER to a string formatted as "class={CLASS_NAME},id={ID}".
#
def reorder
ActiveRecord::Base.transaction do
params['rails_sortable'].each_with_index do |token, new_sort|
next unless token.present?
model = find_model(token)
current_sort = model.read_attribute(model.class.sort_attribute)
model.update_sort!(new_sort) if current_sort != new_sort
end
end
head :ok
end
private
def find_model(token)
klass, id = VERIFIER.verify(token).match(/class=(.+),id=(.+)/)[1..2]
klass.constantize.find(id)
end
end
================================================
FILE: app/models/.keep
================================================
================================================
FILE: app/models/rails_sortable/model.rb
================================================
module RailsSortable
#
# Include this module to your ActiveRecord model.
# And you must call `set_sortable` method for using sortable model.
#
# ex)
# class SampleModel < ActiveRecord::Base
# include RailsSortable::Model
# set_sortable :sort, without_updating_timestamps: true
# end
#
module Model
def self.included(base)
base.class_eval do
before_create :maximize_sort
end
base.extend ClassMethods
end
def update_sort!(new_value)
write_attribute sort_attribute, new_value
if self.class.sortable_options[:silence_recording_timestamps]
warn "[DEPRECATION] `silence_recording_timestamps` is deprecated. Please use `without_updating_timestamps` instead."
without_updating_timestamps { save_as_desired }
elsif self.class.sortable_options[:without_updating_timestamps]
without_updating_timestamps { save_as_desired }
else
save_as_desired
end
end
def sortable_id
SortableController::VERIFIER.generate("class=#{self.class},id=#{self.id}")
end
protected
def maximize_sort
return if read_attribute(sort_attribute)
write_attribute sort_attribute, max_sort
end
def without_updating_timestamps
raise ArgumentError unless block_given?
original_record_timestamps = self.class.record_timestamps
self.class.record_timestamps = false
yield
self.class.record_timestamps = original_record_timestamps
end
def max_sort
(self.class.maximum(sort_attribute) || 0) + 1
end
def save_as_desired
self.class.sortable_options[:without_validations] ? save(validate: false) : save!
end
def sort_attribute
self.class.sort_attribute
end
module ClassMethods
#
# allowed options
# - without_updating_timestamps
# When it is true, timestamp(updated_at) will be NOT touched on reordering.
# - without_validations
# When it is true, validations will be skipped
#
def set_sortable(attribute, options = {})
self.define_singleton_method(:sort_attribute) { attribute }
self.define_singleton_method(:sortable_options) { options }
end
end
end
end
================================================
FILE: bin/bundle
================================================
#!/usr/bin/env ruby
# frozen_string_literal: true
#
# This file was generated by Bundler.
#
# The application 'bundle' is installed as part of a gem, and
# this file is here to facilitate running it.
#
require "rubygems"
m = Module.new do
module_function
def invoked_as_script?
File.expand_path($0) == File.expand_path(__FILE__)
end
def env_var_version
ENV["BUNDLER_VERSION"]
end
def cli_arg_version
return unless invoked_as_script? # don't want to hijack other binstubs
return unless "update".start_with?(ARGV.first || " ") # must be running `bundle update`
bundler_version = nil
update_index = nil
ARGV.each_with_index do |a, i|
if update_index && update_index.succ == i && a =~ Gem::Version::ANCHORED_VERSION_PATTERN
bundler_version = a
end
next unless a =~ /\A--bundler(?:[= ](#{Gem::Version::VERSION_PATTERN}))?\z/
bundler_version = $1 || ">= 0.a"
update_index = i
end
bundler_version
end
def gemfile
gemfile = ENV["BUNDLE_GEMFILE"]
return gemfile if gemfile && !gemfile.empty?
File.expand_path("../../Gemfile", __FILE__)
end
def lockfile
lockfile =
case File.basename(gemfile)
when "gems.rb" then gemfile.sub(/\.rb$/, gemfile)
else "#{gemfile}.lock"
end
File.expand_path(lockfile)
end
def lockfile_version
return unless File.file?(lockfile)
lockfile_contents = File.read(lockfile)
return unless lockfile_contents =~ /\n\nBUNDLED WITH\n\s{2,}(#{Gem::Version::VERSION_PATTERN})\n/
Regexp.last_match(1)
end
def bundler_version
@bundler_version ||= begin
env_var_version || cli_arg_version ||
lockfile_version || "#{Gem::Requirement.default}.a"
end
end
def load_bundler!
ENV["BUNDLE_GEMFILE"] ||= gemfile
# must dup string for RG < 1.8 compatibility
activate_bundler(bundler_version.dup)
end
def activate_bundler(bundler_version)
if Gem::Version.correct?(bundler_version) && Gem::Version.new(bundler_version).release < Gem::Version.new("2.0")
bundler_version = "< 2"
end
gem_error = activation_error_handling do
gem "bundler", bundler_version
end
return if gem_error.nil?
require_error = activation_error_handling do
require "bundler/version"
end
return if require_error.nil? && Gem::Requirement.new(bundler_version).satisfied_by?(Gem::Version.new(Bundler::VERSION))
warn "Activating bundler (#{bundler_version}) failed:\n#{gem_error.message}\n\nTo install the version of bundler this project requires, run `gem install bundler -v '#{bundler_version}'`"
exit 42
end
def activation_error_handling
yield
nil
rescue StandardError, LoadError => e
e
end
end
m.load_bundler!
if m.invoked_as_script?
load Gem.bin_path("bundler", "bundle")
end
================================================
FILE: bin/coderay
================================================
#!/usr/bin/env ruby
# frozen_string_literal: true
#
# This file was generated by Bundler.
#
# The application 'coderay' is installed as part of a gem, and
# this file is here to facilitate running it.
#
require "pathname"
ENV["BUNDLE_GEMFILE"] ||= File.expand_path("../../Gemfile",
Pathname.new(__FILE__).realpath)
bundle_binstub = File.expand_path("../bundle", __FILE__)
if File.file?(bundle_binstub)
if File.read(bundle_binstub, 300) =~ /This file was generated by Bundler/
load(bundle_binstub)
else
abort("Your `bin/bundle` was not generated by Bundler, so this binstub cannot run.
Replace `bin/bundle` by running `bundle binstubs bundler --force`, then run this command again.")
end
end
require "rubygems"
require "bundler/setup"
load Gem.bin_path("coderay", "coderay")
================================================
FILE: bin/htmldiff
================================================
#!/usr/bin/env ruby
# frozen_string_literal: true
#
# This file was generated by Bundler.
#
# The application 'htmldiff' is installed as part of a gem, and
# this file is here to facilitate running it.
#
require "pathname"
ENV["BUNDLE_GEMFILE"] ||= File.expand_path("../../Gemfile",
Pathname.new(__FILE__).realpath)
bundle_binstub = File.expand_path("../bundle", __FILE__)
if File.file?(bundle_binstub)
if File.read(bundle_binstub, 300) =~ /This file was generated by Bundler/
load(bundle_binstub)
else
abort("Your `bin/bundle` was not generated by Bundler, so this binstub cannot run.
Replace `bin/bundle` by running `bundle binstubs bundler --force`, then run this command again.")
end
end
require "rubygems"
require "bundler/setup"
load Gem.bin_path("diff-lcs", "htmldiff")
================================================
FILE: bin/ldiff
================================================
#!/usr/bin/env ruby
# frozen_string_literal: true
#
# This file was generated by Bundler.
#
# The application 'ldiff' is installed as part of a gem, and
# this file is here to facilitate running it.
#
require "pathname"
ENV["BUNDLE_GEMFILE"] ||= File.expand_path("../../Gemfile",
Pathname.new(__FILE__).realpath)
bundle_binstub = File.expand_path("../bundle", __FILE__)
if File.file?(bundle_binstub)
if File.read(bundle_binstub, 300) =~ /This file was generated by Bundler/
load(bundle_binstub)
else
abort("Your `bin/bundle` was not generated by Bundler, so this binstub cannot run.
Replace `bin/bundle` by running `bundle binstubs bundler --force`, then run this command again.")
end
end
require "rubygems"
require "bundler/setup"
load Gem.bin_path("diff-lcs", "ldiff")
================================================
FILE: bin/nokogiri
================================================
#!/usr/bin/env ruby
# frozen_string_literal: true
#
# This file was generated by Bundler.
#
# The application 'nokogiri' is installed as part of a gem, and
# this file is here to facilitate running it.
#
require "pathname"
ENV["BUNDLE_GEMFILE"] ||= File.expand_path("../../Gemfile",
Pathname.new(__FILE__).realpath)
bundle_binstub = File.expand_path("../bundle", __FILE__)
if File.file?(bundle_binstub)
if File.read(bundle_binstub, 300) =~ /This file was generated by Bundler/
load(bundle_binstub)
else
abort("Your `bin/bundle` was not generated by Bundler, so this binstub cannot run.
Replace `bin/bundle` by running `bundle binstubs bundler --force`, then run this command again.")
end
end
require "rubygems"
require "bundler/setup"
load Gem.bin_path("nokogiri", "nokogiri")
================================================
FILE: bin/pry
================================================
#!/usr/bin/env ruby
# frozen_string_literal: true
#
# This file was generated by Bundler.
#
# The application 'pry' is installed as part of a gem, and
# this file is here to facilitate running it.
#
require "pathname"
ENV["BUNDLE_GEMFILE"] ||= File.expand_path("../../Gemfile",
Pathname.new(__FILE__).realpath)
bundle_binstub = File.expand_path("../bundle", __FILE__)
if File.file?(bundle_binstub)
if File.read(bundle_binstub, 300) =~ /This file was generated by Bundler/
load(bundle_binstub)
else
abort("Your `bin/bundle` was not generated by Bundler, so this binstub cannot run.
Replace `bin/bundle` by running `bundle binstubs bundler --force`, then run this command again.")
end
end
require "rubygems"
require "bundler/setup"
load Gem.bin_path("pry", "pry")
================================================
FILE: bin/rackup
================================================
#!/usr/bin/env ruby
# frozen_string_literal: true
#
# This file was generated by Bundler.
#
# The application 'rackup' is installed as part of a gem, and
# this file is here to facilitate running it.
#
require "pathname"
ENV["BUNDLE_GEMFILE"] ||= File.expand_path("../../Gemfile",
Pathname.new(__FILE__).realpath)
bundle_binstub = File.expand_path("../bundle", __FILE__)
if File.file?(bundle_binstub)
if File.read(bundle_binstub, 300) =~ /This file was generated by Bundler/
load(bundle_binstub)
else
abort("Your `bin/bundle` was not generated by Bundler, so this binstub cannot run.
Replace `bin/bundle` by running `bundle binstubs bundler --force`, then run this command again.")
end
end
require "rubygems"
require "bundler/setup"
load Gem.bin_path("rack", "rackup")
================================================
FILE: bin/rails
================================================
#!/usr/bin/env ruby
# frozen_string_literal: true
#
# This file was generated by Bundler.
#
# The application 'rails' is installed as part of a gem, and
# this file is here to facilitate running it.
#
require "pathname"
ENV["BUNDLE_GEMFILE"] ||= File.expand_path("../../Gemfile",
Pathname.new(__FILE__).realpath)
bundle_binstub = File.expand_path("../bundle", __FILE__)
if File.file?(bundle_binstub)
if File.read(bundle_binstub, 300) =~ /This file was generated by Bundler/
load(bundle_binstub)
else
abort("Your `bin/bundle` was not generated by Bundler, so this binstub cannot run.
Replace `bin/bundle` by running `bundle binstubs bundler --force`, then run this command again.")
end
end
require "rubygems"
require "bundler/setup"
load Gem.bin_path("railties", "rails")
================================================
FILE: bin/rake
================================================
#!/usr/bin/env ruby
# frozen_string_literal: true
#
# This file was generated by Bundler.
#
# The application 'rake' is installed as part of a gem, and
# this file is here to facilitate running it.
#
require "pathname"
ENV["BUNDLE_GEMFILE"] ||= File.expand_path("../../Gemfile",
Pathname.new(__FILE__).realpath)
bundle_binstub = File.expand_path("../bundle", __FILE__)
if File.file?(bundle_binstub)
if File.read(bundle_binstub, 300) =~ /This file was generated by Bundler/
load(bundle_binstub)
else
abort("Your `bin/bundle` was not generated by Bundler, so this binstub cannot run.
Replace `bin/bundle` by running `bundle binstubs bundler --force`, then run this command again.")
end
end
require "rubygems"
require "bundler/setup"
load Gem.bin_path("rake", "rake")
================================================
FILE: bin/rspec
================================================
#!/usr/bin/env ruby
# frozen_string_literal: true
#
# This file was generated by Bundler.
#
# The application 'rspec' is installed as part of a gem, and
# this file is here to facilitate running it.
#
require "pathname"
ENV["BUNDLE_GEMFILE"] ||= File.expand_path("../../Gemfile",
Pathname.new(__FILE__).realpath)
bundle_binstub = File.expand_path("../bundle", __FILE__)
if File.file?(bundle_binstub)
if File.read(bundle_binstub, 300) =~ /This file was generated by Bundler/
load(bundle_binstub)
else
abort("Your `bin/bundle` was not generated by Bundler, so this binstub cannot run.
Replace `bin/bundle` by running `bundle binstubs bundler --force`, then run this command again.")
end
end
require "rubygems"
require "bundler/setup"
load Gem.bin_path("rspec-core", "rspec")
================================================
FILE: bin/sprockets
================================================
#!/usr/bin/env ruby
# frozen_string_literal: true
#
# This file was generated by Bundler.
#
# The application 'sprockets' is installed as part of a gem, and
# this file is here to facilitate running it.
#
require "pathname"
ENV["BUNDLE_GEMFILE"] ||= File.expand_path("../../Gemfile",
Pathname.new(__FILE__).realpath)
bundle_binstub = File.expand_path("../bundle", __FILE__)
if File.file?(bundle_binstub)
if File.read(bundle_binstub, 300) =~ /This file was generated by Bundler/
load(bundle_binstub)
else
abort("Your `bin/bundle` was not generated by Bundler, so this binstub cannot run.
Replace `bin/bundle` by running `bundle binstubs bundler --force`, then run this command again.")
end
end
require "rubygems"
require "bundler/setup"
load Gem.bin_path("sprockets", "sprockets")
================================================
FILE: bin/thor
================================================
#!/usr/bin/env ruby
# frozen_string_literal: true
#
# This file was generated by Bundler.
#
# The application 'thor' is installed as part of a gem, and
# this file is here to facilitate running it.
#
require "pathname"
ENV["BUNDLE_GEMFILE"] ||= File.expand_path("../../Gemfile",
Pathname.new(__FILE__).realpath)
bundle_binstub = File.expand_path("../bundle", __FILE__)
if File.file?(bundle_binstub)
if File.read(bundle_binstub, 300) =~ /This file was generated by Bundler/
load(bundle_binstub)
else
abort("Your `bin/bundle` was not generated by Bundler, so this binstub cannot run.
Replace `bin/bundle` by running `bundle binstubs bundler --force`, then run this command again.")
end
end
require "rubygems"
require "bundler/setup"
load Gem.bin_path("thor", "thor")
================================================
FILE: config/routes.rb
================================================
Rails.application.routes.draw do
post "/sortable/reorder", to: "sortable#reorder"
end
================================================
FILE: lib/rails_sortable/core_ext/enumerable.rb
================================================
module Enumerable
def each_with_sortable_id(&block)
raise "Must be called with block!" unless block_given?
each { |e| yield e, e.sortable_id }
end
end
================================================
FILE: lib/rails_sortable/core_ext.rb
================================================
Dir.glob(File.expand_path('core_ext/*.rb', File.dirname(__FILE__))).each do |path|
require path
end
================================================
FILE: lib/rails_sortable/engine.rb
================================================
module RailsSortable
class Engine < ::Rails::Engine
end
end
================================================
FILE: lib/rails_sortable/version.rb
================================================
module RailsSortable
VERSION = '1.6.0'
end
================================================
FILE: lib/rails_sortable.rb
================================================
require "rails_sortable/engine"
require "rails_sortable/core_ext"
module RailsSortable
end
================================================
FILE: rails_sortable.gemspec
================================================
$:.push File.expand_path("../lib", __FILE__)
# Maintain your gem's version:
require "rails_sortable/version"
# Describe your gem and declare its dependencies:
Gem::Specification.new do |s|
s.name = "rails_sortable"
s.version = RailsSortable::VERSION
s.authors = ["itmammoth"]
s.email = ["itmammoth@gmail.com"]
s.homepage = "https://github.com/itmammoth/rails_sortable"
s.summary = "Easy drag & drop sorting for rails."
s.description = "rails_sortable provides easy drag & drop sorting for rails 4 and 5."
s.licenses = ['MIT']
s.files = Dir["{app,config,lib,vendor/assets}/**/*", "LICENSE", "Rakefile", "README.md"]
s.test_files = `git ls-files spec`.split("\n")
s.add_development_dependency "rails", "~> 6.0.0"
s.add_development_dependency "jquery-rails", "~> 4.3.0"
s.add_development_dependency "jquery-ui-rails", "~> 6.0.0"
s.add_development_dependency "sqlite3", "~> 1.4.0"
s.add_development_dependency "rspec-rails", "~> 3.9.0"
s.add_development_dependency "pry-rails", "~> 0.3.0"
s.add_development_dependency "puma", "~> 5.6.0"
end
================================================
FILE: spec/controllers/sortable_controller_spec.rb
================================================
require 'spec_helper'
def create_token(klass, id)
return SortableController::VERIFIER.generate("class=#{klass},id=#{id}")
end
describe SortableController, type: :controller do
describe 'POST reorder' do
before do
@item1 = Item.create!
@item2 = Item.create!
@item3 = Item.create!
end
it 'should reorder models' do
data = [
create_token('Item', @item1.to_param),
create_token('Item', @item3.to_param),
create_token('Item', @item2.to_param),
]
if Gem::Version.new(Rails.version) < Gem::Version.new(5)
post :reorder, rails_sortable: data
else
post :reorder, params: { rails_sortable: data }
end
expect(response.body).to be_blank
expect(Item.find(@item1.id).sort).to eql 0
expect(Item.find(@item2.id).sort).to eql 2
expect(Item.find(@item3.id).sort).to eql 1
end
end
describe 'POST reorder with multiple classes' do
before do
@first_item1 = FirstItem.create!
@first_item2 = FirstItem.create!
@second_item1 = SecondItem.create!
@second_item2 = SecondItem.create!
end
it 'should reorder models' do
data = [
create_token('SecondItem', @second_item2.to_param),
create_token('FirstItem', @first_item2.to_param),
create_token('FirstItem', @first_item1.to_param),
create_token('SecondItem', @second_item1.to_param),
]
if Gem::Version.new(Rails.version) < Gem::Version.new(5)
post :reorder, rails_sortable: data
else
post :reorder, params: { rails_sortable: data }
end
expect(response.body).to be_blank
expect(SecondItem.find(@second_item2.id).sort).to eql 0
expect(FirstItem.find(@first_item2.id).sort).to eql 1
expect(FirstItem.find(@first_item1.id).sort).to eql 2
expect(SecondItem.find(@second_item1.id).sort).to eql 3
end
end
end
================================================
FILE: spec/dummy/README.rdoc
================================================
== README
This README would normally document whatever steps are necessary to get the
application up and running.
Things you may want to cover:
* Ruby version
* System dependencies
* Configuration
* Database creation
* Database initialization
* How to run the test suite
* Services (job queues, cache servers, search engines, etc.)
* Deployment instructions
* ...
Please feel free to use a different markup language if you do not plan to run
rake doc:app.
================================================
FILE: spec/dummy/Rakefile
================================================
# Add your own tasks in files placed in lib/tasks ending in .rake,
# for example lib/tasks/capistrano.rake, and they will automatically be available to Rake.
require File.expand_path('../config/application', __FILE__)
Dummy::Application.load_tasks
================================================
FILE: spec/dummy/app/assets/config/manifest.js
================================================
//= link_tree ../images
//= link_directory ../javascripts .js
//= link_directory ../stylesheets .css
================================================
FILE: spec/dummy/app/assets/images/.keep
================================================
================================================
FILE: spec/dummy/app/assets/javascripts/application.js
================================================
// This is a manifest file that'll be compiled into application.js, which will include all the files
// listed below.
//
// Any JavaScript/Coffee file within this directory, lib/assets/javascripts, vendor/assets/javascripts,
// or vendor/assets/javascripts of plugins, if any, can be referenced here using a relative path.
//
// It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the
// compiled file.
//
// Read Sprockets README (https://github.com/sstephenson/sprockets#sprockets-directives) for details
// about supported directives.
//
//= require jquery
//= require jquery_ujs
//= require jquery-ui/widgets/sortable
//= require rails_sortable
//= require_tree .
================================================
FILE: spec/dummy/app/assets/javascripts/items.js
================================================
(function($) {
$(".sortable-items").railsSortable({
update: function(event, ui) {
console.log('Yay! RailsSortable never spoil your implementation for sotable events.');
console.log(event, ui);
},
});
})(jQuery);
================================================
FILE: spec/dummy/app/assets/javascripts/multiple_classes.js
================================================
(function($) {
$(".sortable-multiple-classes").railsSortable();
})(jQuery);
================================================
FILE: spec/dummy/app/assets/javascripts/sequenced_items.js
================================================
(function($) {
$(".sortable-sequenced-items").railsSortable();
})(jQuery);
================================================
FILE: spec/dummy/app/assets/stylesheets/application.css
================================================
/*
* This is a manifest file that'll be compiled into application.css, which will include all the files
* listed below.
*
* Any CSS and SCSS file within this directory, lib/assets/stylesheets, vendor/assets/stylesheets,
* or vendor/assets/stylesheets of plugins, if any, can be referenced here using a relative path.
*
* You're free to add application-wide styles to this file and they'll appear at the top of the
* compiled file, but it's generally better to create a new file per style scope.
*
*= require_self
*= require_tree .
*/
================================================
FILE: spec/dummy/app/assets/stylesheets/scaffold.css
================================================
body { background-color: #fff; color: #333; }
body, p, ol, ul, td {
font-family: verdana, arial, helvetica, sans-serif;
font-size: 13px;
line-height: 18px;
}
pre {
background-color: #eee;
padding: 10px;
font-size: 11px;
}
a { color: #000; }
a:visited { color: #666; }
a:hover { color: #fff; background-color:#000; }
div.field, div.actions {
margin-bottom: 10px;
}
#notice {
color: green;
}
.field_with_errors {
padding: 2px;
background-color: red;
display: table;
}
#error_explanation {
width: 450px;
border: 2px solid red;
padding: 7px;
padding-bottom: 0;
margin-bottom: 20px;
background-color: #f0f0f0;
}
#error_explanation h2 {
text-align: left;
font-weight: bold;
padding: 5px 5px 5px 15px;
font-size: 12px;
margin: -7px;
margin-bottom: 0px;
background-color: #c00;
color: #fff;
}
#error_explanation ul li {
font-size: 12px;
list-style: square;
}
================================================
FILE: spec/dummy/app/controllers/application_controller.rb
================================================
class ApplicationController < ActionController::Base
# Prevent CSRF attacks by raising an exception.
# For APIs, you may want to use :null_session instead.
protect_from_forgery with: :exception
end
================================================
FILE: spec/dummy/app/controllers/concerns/.keep
================================================
================================================
FILE: spec/dummy/app/controllers/items_controller.rb
================================================
class ItemsController < ApplicationController
before_action :set_item, only: [:show, :edit, :update, :destroy]
# GET /items
def index
@items = Item.all
end
# GET /items/1
def show
end
# GET /items/new
def new
@item = Item.new
end
# GET /items/1/edit
def edit
end
# POST /items
def create
@item = Item.new(item_params)
if @item.save
redirect_to @item, notice: 'Item was successfully created.'
else
render action: 'new'
end
end
# PATCH/PUT /items/1
def update
if @item.update(item_params)
redirect_to @item, notice: 'Item was successfully updated.'
else
render action: 'edit'
end
end
# DELETE /items/1
def destroy
@item.destroy
redirect_to items_url, notice: 'Item was successfully destroyed.'
end
private
# Use callbacks to share common setup or constraints between actions.
def set_item
@item = Item.find(params[:id])
end
# Only allow a trusted parameter "white list" through.
def item_params
params.require(:item).permit(:title, :sort)
end
end
================================================
FILE: spec/dummy/app/controllers/multiple_classes_controller.rb
================================================
class MultipleClassesController < ApplicationController
# GET /multiple_classes
def index
@items = (FirstItem.all + SecondItem.all).sort_by(&:sort)
end
end
================================================
FILE: spec/dummy/app/controllers/sequenced_items_controller.rb
================================================
class SequencedItemsController < ApplicationController
before_action :set_sequenced_item, only: [:show, :edit, :update, :destroy]
# GET /sequenced_items
def index
@sequenced_items = SequencedItem.all
end
# GET /sequenced_items/1
def show
end
# GET /sequenced_items/new
def new
@sequenced_item = SequencedItem.new
end
# GET /sequenced_items/1/edit
def edit
end
# POST /sequenced_items
def create
@sequenced_item = SequencedItem.new(sequenced_item_params)
if @sequenced_item.save
redirect_to @sequenced_item, notice: 'Other item was successfully created.'
else
render action: 'new'
end
end
# PATCH/PUT /sequenced_items/1
def update
if @sequenced_item.update(sequenced_item_params)
redirect_to @sequenced_item, notice: 'Other item was successfully updated.'
else
render action: 'edit'
end
end
# DELETE /sequenced_items/1
def destroy
@sequenced_item.destroy
redirect_to sequenced_items_url, notice: 'Other item was successfully destroyed.'
end
private
# Use callbacks to share common setup or constraints between actions.
def set_sequenced_item
@sequenced_item = SequencedItem.find(params[:id])
end
# Only allow a trusted parameter "white list" through.
def sequenced_item_params
params.require(:sequenced_item).permit(:title, :sequence)
end
end
================================================
FILE: spec/dummy/app/models/.keep
================================================
================================================
FILE: spec/dummy/app/models/concerns/.keep
================================================
================================================
FILE: spec/dummy/app/models/first_item.rb
================================================
class FirstItem < ActiveRecord::Base
include RailsSortable::Model
set_sortable :sort
default_scope -> { order(:sort) }
end
================================================
FILE: spec/dummy/app/models/item.rb
================================================
class Item < ActiveRecord::Base
include RailsSortable::Model
set_sortable :sort
default_scope -> { order(:sort) }
end
================================================
FILE: spec/dummy/app/models/second_item.rb
================================================
class SecondItem < ActiveRecord::Base
include RailsSortable::Model
set_sortable :sort
default_scope -> { order(:sort) }
end
================================================
FILE: spec/dummy/app/models/sequenced_item.rb
================================================
class SequencedItem < ActiveRecord::Base
include RailsSortable::Model
set_sortable :sequence, without_updating_timestamps: true
default_scope -> { order(:sequence) }
end
================================================
FILE: spec/dummy/app/models/validated_item.rb
================================================
class ValidatedItem < Item
self.table_name = "items"
validates_presence_of :title
end
================================================
FILE: spec/dummy/app/views/items/_form.html.erb
================================================
<%= form_for(@item) do |f| %>
<% if @item.errors.any? %>
<%= pluralize(@item.errors.count, "error") %> prohibited this item from being saved:
<% @item.errors.full_messages.each do |msg| %>
- <%= msg %>
<% end %>
<% end %>
<%= f.label :title %>
<%= f.text_field :title %>
<%= f.label :sort %>
<%= f.number_field :sort %>
<%= f.submit %>
<% end %>
================================================
FILE: spec/dummy/app/views/items/edit.html.erb
================================================
Editing item
<%= render 'form' %>
<%= link_to 'Show', @item %> |
<%= link_to 'Back', items_path %>
================================================
FILE: spec/dummy/app/views/items/index.html.erb
================================================
Listing items
| Title |
Sort |
Updated at |
|
|
|
<% @items.each_with_sortable_id do |item, sortable_id| %>
| <%= item.title %> |
<%= item.sort %> |
<%= item.updated_at %> |
<%= link_to 'Show', item %> |
<%= link_to 'Edit', edit_item_path(item) %> |
<%= link_to 'Destroy', item, method: :delete, data: { confirm: 'Are you sure?' } %> |
<% end %>
<%= link_to 'New Item', new_item_path %>
================================================
FILE: spec/dummy/app/views/items/new.html.erb
================================================
New item
<%= render 'form' %>
<%= link_to 'Back', items_path %>
================================================
FILE: spec/dummy/app/views/items/show.html.erb
================================================
<%= notice %>
Title:
<%= @item.title %>
Sort:
<%= @item.sort %>
<%= link_to 'Edit', edit_item_path(@item) %> |
<%= link_to 'Back', items_path %>
================================================
FILE: spec/dummy/app/views/layouts/application.html.erb
================================================
Dummy
<%= stylesheet_link_tag "application", media: "all", "data-turbolinks-track" => true, :defer => true %>
<%= javascript_include_tag "application", "data-turbolinks-track" => true, :defer => true %>
<%= csrf_meta_tags %>
<%= yield %>
================================================
FILE: spec/dummy/app/views/multiple_classes/index.html.erb
================================================
Listing multiple class items
| Title |
Sort |
Updated at |
|
|
|
<% @items.each_with_sortable_id do |item, sortable_id| %>
| <%= item.title %> |
<%= item.sort %> |
<%= item.updated_at %> |
<% end %>
================================================
FILE: spec/dummy/app/views/sequenced_items/_form.html.erb
================================================
<%= form_for(@sequenced_item) do |f| %>
<% if @sequenced_item.errors.any? %>
<%= pluralize(@sequenced_item.errors.count, "error") %> prohibited this sequenced_item from being saved:
<% @sequenced_item.errors.full_messages.each do |msg| %>
- <%= msg %>
<% end %>
<% end %>
<%= f.label :title %>
<%= f.text_field :title %>
<%= f.label :sequence %>
<%= f.number_field :sequence %>
<%= f.submit %>
<% end %>
================================================
FILE: spec/dummy/app/views/sequenced_items/edit.html.erb
================================================
Editing sequenced_item
<%= render 'form' %>
<%= link_to 'Show', @sequenced_item %> |
<%= link_to 'Back', sequenced_items_path %>
================================================
FILE: spec/dummy/app/views/sequenced_items/index.html.erb
================================================
Listing sequenced_items
| Title |
Sequence |
Updated at |
|
|
|
<% @sequenced_items.each_with_sortable_id do |sequenced_item, sortable_id| %>
| <%= sequenced_item.title %> |
<%= sequenced_item.sequence %> |
<%= sequenced_item.updated_at %> |
<%= link_to 'Show', sequenced_item %> |
<%= link_to 'Edit', edit_sequenced_item_path(sequenced_item) %> |
<%= link_to 'Destroy', sequenced_item, method: :delete, data: { confirm: 'Are you sure?' } %> |
<% end %>
<%= link_to 'New Sequenced item', new_sequenced_item_path %>
================================================
FILE: spec/dummy/app/views/sequenced_items/new.html.erb
================================================
New sequenced_item
<%= render 'form' %>
<%= link_to 'Back', sequenced_items_path %>
================================================
FILE: spec/dummy/app/views/sequenced_items/show.html.erb
================================================
<%= notice %>
Title:
<%= @sequenced_item.title %>
Sequence:
<%= @sequenced_item.sequence %>
<%= link_to 'Edit', edit_sequenced_item_path(@sequenced_item) %> |
<%= link_to 'Back', sequenced_items_path %>
================================================
FILE: spec/dummy/bin/bundle
================================================
#!/usr/bin/env ruby
ENV['BUNDLE_GEMFILE'] ||= File.expand_path('../../Gemfile', __FILE__)
load Gem.bin_path('bundler', 'bundle')
================================================
FILE: spec/dummy/bin/rails
================================================
#!/usr/bin/env ruby
APP_PATH = File.expand_path('../../config/application', __FILE__)
require_relative '../config/boot'
require 'rails/commands'
================================================
FILE: spec/dummy/bin/rake
================================================
#!/usr/bin/env ruby
require_relative '../config/boot'
require 'rake'
Rake.application.run
================================================
FILE: spec/dummy/config/application.rb
================================================
require File.expand_path('../boot', __FILE__)
# Pick the frameworks you want:
require "active_record/railtie"
require "action_controller/railtie"
require "action_mailer/railtie"
require "sprockets/railtie"
# require "rails/test_unit/railtie"
Bundler.require(*Rails.groups)
require "rails_sortable"
module Dummy
class Application < Rails::Application
# Settings in config/environments/* take precedence over those specified here.
# Application configuration should go into files in config/initializers
# -- all .rb files in that directory are automatically loaded.
# Set Time.zone default to the specified zone and make Active Record auto-convert to this zone.
# Run "rake -D time" for a list of tasks for finding time zone names. Default is UTC.
# config.time_zone = 'Central Time (US & Canada)'
# The default locale is :en and all translations from config/locales/*.rb,yml are auto loaded.
# config.i18n.load_path += Dir[Rails.root.join('my', 'locales', '*.{rb,yml}').to_s]
# config.i18n.default_locale = :de
end
MigrationClass = Gem::Version.new(Rails.version) < Gem::Version.new(5) ? ActiveRecord::Migration : ActiveRecord::Migration[4.2]
end
================================================
FILE: spec/dummy/config/boot.rb
================================================
# Set up gems listed in the Gemfile.
ENV['BUNDLE_GEMFILE'] ||= File.expand_path('../../../../Gemfile', __FILE__)
require 'bundler/setup' if File.exists?(ENV['BUNDLE_GEMFILE'])
$LOAD_PATH.unshift File.expand_path('../../../../lib', __FILE__)
================================================
FILE: spec/dummy/config/database.yml
================================================
# SQLite version 3.x
# gem install sqlite3
#
# Ensure the SQLite 3 gem is defined in your Gemfile
# gem 'sqlite3'
development:
adapter: sqlite3
database: db/development.sqlite3
pool: 5
timeout: 5000
# Warning: The database defined as "test" will be erased and
# re-generated from your development database when you run "rake".
# Do not set this db to the same as development or production.
test:
adapter: sqlite3
database: db/test.sqlite3
pool: 5
timeout: 5000
production:
adapter: sqlite3
database: db/production.sqlite3
pool: 5
timeout: 5000
================================================
FILE: spec/dummy/config/environment.rb
================================================
# Load the Rails application.
require File.expand_path('../application', __FILE__)
# Initialize the Rails application.
Dummy::Application.initialize!
================================================
FILE: spec/dummy/config/environments/development.rb
================================================
Dummy::Application.configure do
# Settings specified here will take precedence over those in config/application.rb.
# In the development environment your application's code is reloaded on
# every request. This slows down response time but is perfect for development
# since you don't have to restart the web server when you make code changes.
config.cache_classes = false
# Do not eager load code on boot.
config.eager_load = false
# Show full error reports and disable caching.
config.consider_all_requests_local = true
config.action_controller.perform_caching = false
# Don't care if the mailer can't send.
config.action_mailer.raise_delivery_errors = false
# Print deprecation notices to the Rails logger.
config.active_support.deprecation = :log
# Raise an error on page load if there are pending migrations
config.active_record.migration_error = :page_load
# Debug mode disables concatenation and preprocessing of assets.
# This option may cause significant delays in view rendering with a large
# number of complex assets.
config.assets.debug = true
end
================================================
FILE: spec/dummy/config/environments/production.rb
================================================
Dummy::Application.configure do
# Settings specified here will take precedence over those in config/application.rb.
# Code is not reloaded between requests.
config.cache_classes = true
# Eager load code on boot. This eager loads most of Rails and
# your application in memory, allowing both thread web servers
# and those relying on copy on write to perform better.
# Rake tasks automatically ignore this option for performance.
config.eager_load = true
# Full error reports are disabled and caching is turned on.
config.consider_all_requests_local = false
config.action_controller.perform_caching = true
# Enable Rack::Cache to put a simple HTTP cache in front of your application
# Add `rack-cache` to your Gemfile before enabling this.
# For large-scale production use, consider using a caching reverse proxy like nginx, varnish or squid.
# config.action_dispatch.rack_cache = true
# Disable Rails's static asset server (Apache or nginx will already do this).
if Gem::Version.new(Rails.version) < Gem::Version.new(5)
config.serve_static_files = false
else
config.public_file_server.enabled = false
end
# Compress JavaScripts and CSS.
config.assets.js_compressor = :uglifier
# config.assets.css_compressor = :sass
# Do not fallback to assets pipeline if a precompiled asset is missed.
config.assets.compile = false
# Generate digests for assets URLs.
config.assets.digest = true
# Version of your assets, change this if you want to expire all your assets.
config.assets.version = '1.0'
# Specifies the header that your server uses for sending files.
# config.action_dispatch.x_sendfile_header = "X-Sendfile" # for apache
# config.action_dispatch.x_sendfile_header = 'X-Accel-Redirect' # for nginx
# Force all access to the app over SSL, use Strict-Transport-Security, and use secure cookies.
# config.force_ssl = true
# Set to :debug to see everything in the log.
config.log_level = :info
# Prepend all log lines with the following tags.
# config.log_tags = [ :subdomain, :uuid ]
# Use a different logger for distributed setups.
# config.logger = ActiveSupport::TaggedLogging.new(SyslogLogger.new)
# Use a different cache store in production.
# config.cache_store = :mem_cache_store
# Enable serving of images, stylesheets, and JavaScripts from an asset server.
# config.action_controller.asset_host = "http://assets.example.com"
# Precompile additional assets.
# application.js, application.css, and all non-JS/CSS in app/assets folder are already added.
# config.assets.precompile += %w( search.js )
# Ignore bad email addresses and do not raise email delivery errors.
# Set this to true and configure the email server for immediate delivery to raise delivery errors.
# config.action_mailer.raise_delivery_errors = false
# Enable locale fallbacks for I18n (makes lookups for any locale fall back to
# the I18n.default_locale when a translation can not be found).
config.i18n.fallbacks = [I18n.default_locale]
# Send deprecation notices to registered listeners.
config.active_support.deprecation = :notify
# Disable automatic flushing of the log to improve performance.
# config.autoflush_log = false
# Use default logging formatter so that PID and timestamp are not suppressed.
config.log_formatter = ::Logger::Formatter.new
end
================================================
FILE: spec/dummy/config/environments/test.rb
================================================
Dummy::Application.configure do
# Settings specified here will take precedence over those in config/application.rb.
# The test environment is used exclusively to run your application's
# test suite. You never need to work with it otherwise. Remember that
# your test database is "scratch space" for the test suite and is wiped
# and recreated between test runs. Don't rely on the data there!
config.cache_classes = true
# Do not eager load code on boot. This avoids loading your whole application
# just for the purpose of running a single test. If you are using a tool that
# preloads Rails for running tests, you may have to set it to true.
config.eager_load = false
# Configure static asset server for tests with Cache-Control for performance.
if Gem::Version.new(Rails.version) < Gem::Version.new(5)
config.serve_static_files = true
config.static_cache_control = "public, max-age=3600"
else
config.public_file_server.enabled = true
config.public_file_server.headers = "public, max-age=3600"
end
# Show full error reports and disable caching.
config.consider_all_requests_local = true
config.action_controller.perform_caching = false
# Raise exceptions instead of rendering exception templates.
config.action_dispatch.show_exceptions = false
# Disable request forgery protection in test environment.
config.action_controller.allow_forgery_protection = false
# Tell Action Mailer not to deliver emails to the real world.
# The :test delivery method accumulates sent emails in the
# ActionMailer::Base.deliveries array.
config.action_mailer.delivery_method = :test
# Print deprecation notices to the stderr.
config.active_support.deprecation = :stderr
end
================================================
FILE: spec/dummy/config/initializers/backtrace_silencers.rb
================================================
# Be sure to restart your server when you modify this file.
# You can add backtrace silencers for libraries that you're using but don't wish to see in your backtraces.
# Rails.backtrace_cleaner.add_silencer { |line| line =~ /my_noisy_library/ }
# You can also remove all the silencers if you're trying to debug a problem that might stem from framework code.
# Rails.backtrace_cleaner.remove_silencers!
================================================
FILE: spec/dummy/config/initializers/filter_parameter_logging.rb
================================================
# Be sure to restart your server when you modify this file.
# Configure sensitive parameters which will be filtered from the log file.
Rails.application.config.filter_parameters += [:password]
================================================
FILE: spec/dummy/config/initializers/inflections.rb
================================================
# Be sure to restart your server when you modify this file.
# Add new inflection rules using the following format. Inflections
# are locale specific, and you may define rules for as many different
# locales as you wish. All of these examples are active by default:
# ActiveSupport::Inflector.inflections(:en) do |inflect|
# inflect.plural /^(ox)$/i, '\1en'
# inflect.singular /^(ox)en/i, '\1'
# inflect.irregular 'person', 'people'
# inflect.uncountable %w( fish sheep )
# end
# These inflection rules are supported but not enabled by default:
# ActiveSupport::Inflector.inflections(:en) do |inflect|
# inflect.acronym 'RESTful'
# end
================================================
FILE: spec/dummy/config/initializers/mime_types.rb
================================================
# Be sure to restart your server when you modify this file.
# Add new mime types for use in respond_to blocks:
# Mime::Type.register "text/richtext", :rtf
# Mime::Type.register_alias "text/html", :iphone
================================================
FILE: spec/dummy/config/initializers/secret_token.rb
================================================
# Be sure to restart your server when you modify this file.
# Your secret key is used for verifying the integrity of signed cookies.
# If you change this key, all old signed cookies will become invalid!
# Make sure the secret is at least 30 characters and all random,
# no regular words or you'll be exposed to dictionary attacks.
# You can use `rake secret` to generate a secure secret key.
# Make sure your secret_key_base is kept private
# if you're sharing your code publicly.
Dummy::Application.config.secret_key_base = 'f98fee0850aaebc8971433d0397b6c79309df33a5e2a24276c89f5457d4ba65b0386d6657f2eb65411b5a5e429114b45b7f92f8300762331a677d3747f774190'
================================================
FILE: spec/dummy/config/initializers/session_store.rb
================================================
# Be sure to restart your server when you modify this file.
Dummy::Application.config.session_store :cookie_store, key: '_dummy_session'
================================================
FILE: spec/dummy/config/initializers/wrap_parameters.rb
================================================
# Be sure to restart your server when you modify this file.
# This file contains settings for ActionController::ParamsWrapper which
# is enabled by default.
# Enable parameter wrapping for JSON. You can disable this by setting :format to an empty array.
ActiveSupport.on_load(:action_controller) do
wrap_parameters format: [:json] if respond_to?(:wrap_parameters)
end
# To enable root element in JSON for ActiveRecord objects.
# ActiveSupport.on_load(:active_record) do
# self.include_root_in_json = true
# end
================================================
FILE: spec/dummy/config/locales/en.yml
================================================
# Files in the config/locales directory are used for internationalization
# and are automatically loaded by Rails. If you want to use locales other
# than English, add the necessary files in this directory.
#
# To use the locales, use `I18n.t`:
#
# I18n.t 'hello'
#
# In views, this is aliased to just `t`:
#
# <%= t('hello') %>
#
# To use a different locale, set it with `I18n.locale`:
#
# I18n.locale = :es
#
# This would use the information in config/locales/es.yml.
#
# To learn more, please read the Rails Internationalization guide
# available at http://guides.rubyonrails.org/i18n.html.
en:
hello: "Hello world"
================================================
FILE: spec/dummy/config/routes.rb
================================================
Dummy::Application.routes.draw do
resources :items
resources :sequenced_items
get 'multiple_classes', to: 'multiple_classes#index'
end
================================================
FILE: spec/dummy/config.ru
================================================
# This file is used by Rack-based servers to start the application.
require ::File.expand_path('../config/environment', __FILE__)
run Rails.application
================================================
FILE: spec/dummy/db/migrate/20131223124841_create_items.rb
================================================
class CreateItems < Dummy::MigrationClass
def change
create_table :items do |t|
t.string :title
t.integer :sort
t.timestamps null: false
end
end
end
================================================
FILE: spec/dummy/db/migrate/20170414031946_create_sequenced_items.rb
================================================
class CreateSequencedItems < Dummy::MigrationClass
def change
create_table :sequenced_items do |t|
t.string :title
t.integer :sequence
t.timestamps null: false
end
end
end
================================================
FILE: spec/dummy/db/migrate/20180427061457_create_multiple_classes.rb
================================================
class CreateMultipleClasses < Dummy::MigrationClass
def change
create_table :first_items do |t|
t.string :title
t.integer :sort
t.timestamps null: false
end
create_table :second_items do |t|
t.string :title
t.integer :sort
t.timestamps null: false
end
end
end
================================================
FILE: spec/dummy/db/seeds.rb
================================================
Item.delete_all
10.times {|i| Item.create! title: "Title#{i}", sort: i }
SequencedItem.delete_all
10.times {|i| SequencedItem.create! title: "OtherTitle#{i}", sequence: i }
FirstItem.delete_all
(0..4).each {|i| FirstItem.create! title: "FirstTitle#{i}", sort: i }
SecondItem.delete_all
(5..9).each {|i| SecondItem.create! title: "SecondTitle#{i}", sort: i }
================================================
FILE: spec/dummy/lib/assets/.keep
================================================
================================================
FILE: spec/dummy/log/.keep
================================================
================================================
FILE: spec/dummy/public/404.html
================================================
The page you were looking for doesn't exist (404)
The page you were looking for doesn't exist.
You may have mistyped the address or the page may have moved.
If you are the application owner check the logs for more information.
================================================
FILE: spec/dummy/public/422.html
================================================
The change you wanted was rejected (422)
The change you wanted was rejected.
Maybe you tried to change something you didn't have access to.
If you are the application owner check the logs for more information.
================================================
FILE: spec/dummy/public/500.html
================================================
We're sorry, but something went wrong (500)
We're sorry, but something went wrong.
If you are the application owner check the logs for more information.
================================================
FILE: spec/models/rails_sortable/model_spec.rb
================================================
require 'spec_helper'
describe RailsSortable::Model, type: :model do
describe "before_create" do
context "when sort is nil" do
it "should be automatically set maximum sort value" do
Item.create! sort: 1000
new_item = Item.create!
expect(new_item.sort).to eql 1001
end
end
context "when sort has value" do
it "should not set sort value" do
item = Item.create! sort: 1000
expect(item.sort).to eql 1000
end
end
end
describe "set_sortable" do
describe "attribute" do
it "should change sort_attribute" do
other_item = SequencedItem.create!
expect(other_item.sequence).to eql(1)
end
end
describe "without_updating_timestamps" do
context "when optional value is true" do
before do
Item.class_eval do
set_sortable :sort, without_updating_timestamps: true
end
end
it "should NOT modify timestamps" do
item = Item.create!
expect { item.update_sort!(1000) }.to_not change(item, :updated_at)
end
end
context "when optional value is NOT true" do
before do
Item.class_eval do
set_sortable :sort, without_updating_timestamps: false
end
end
it "should modify timestamps" do
item = Item.create!
expect { item.update_sort!(1000) }.to change(item, :updated_at)
end
end
end
describe "without_validations" do
context "when optional value is true" do
before do
ValidatedItem.class_eval do
set_sortable :sort, without_validations: true
end
end
it "will skip validations" do
item = ValidatedItem.create!(title: "Title")
item.update_attribute(:title, nil)
expect { item.update_sort!(1000) }.not_to raise_error
end
end
context "when optional value is false" do
before do
ValidatedItem.class_eval do
set_sortable :sort, without_validations: false
end
end
it "will require validations" do
item = ValidatedItem.create!(title: "Title")
item.update_attribute(:title, nil)
expect do
item.update_sort!(1000)
end.to raise_error(ActiveRecord::RecordInvalid, /Title can't be blank/)
end
end
end
end
describe "sortable_id" do
it "should return a correct sortable_id" do
item = Item.create!
expect(item.sortable_id).to eq(SortableController::VERIFIER.generate("class=Item,id=#{item.to_param}"))
end
end
describe "each_with_sortable_id" do
it "should make models iterable with sortable ids" do
items = 2.times.map { |i| Item.create! sort: i }
expect { |b| Item.order(:sort).each_with_sortable_id(&b) }.to yield_successive_args(
[items[0], SortableController::VERIFIER.generate("class=Item,id=#{items[0].to_param}")],
[items[1], SortableController::VERIFIER.generate("class=Item,id=#{items[1].to_param}")],
)
end
end
end
================================================
FILE: spec/spec_helper.rb
================================================
# This file is copied to spec/ when you run 'rails generate rspec:install'
ENV["RAILS_ENV"] ||= 'test'
require File.expand_path("../dummy/config/environment", __FILE__)
require 'rspec/rails'
# Requires supporting ruby files with custom matchers and macros, etc,
# in spec/support/ and its subdirectories.
Dir[Rails.root.join("spec/support/**/*.rb")].each { |f| require f }
# Checks for pending migrations before tests are run.
# If you are not using ActiveRecord, you can remove this line.
ActiveRecord::Migration.check_pending! if defined?(ActiveRecord::Migration)
RSpec.configure do |config|
# ## Mock Framework
#
# If you prefer to use mocha, flexmock or RR, uncomment the appropriate line:
#
# config.mock_with :mocha
# config.mock_with :flexmock
# config.mock_with :rr
# Remove this line if you're not using ActiveRecord or ActiveRecord fixtures
config.fixture_path = "#{::Rails.root}/spec/fixtures"
# If you're not using ActiveRecord, or you'd prefer not to run each of your
# examples within a transaction, remove the following line or assign false
# instead of true.
config.use_transactional_fixtures = true
# If true, the base class of anonymous controllers will be inferred
# automatically. This will be the default behavior in future versions of
# rspec-rails.
config.infer_base_class_for_anonymous_controllers = false
# Run specs in random order to surface order dependencies. If you find an
# order dependency and want to debug it, you can fix the order by providing
# the seed, which is printed after each run.
# --seed 1234
config.order = "random"
end
# Workaround for ThreadError: already initialized with Ruby 2.6.0
# See https://github.com/rails/rails/issues/34790
if RUBY_VERSION >= '2.6.0'
if Rails.version < '5'
class ActionController::TestResponse < ActionDispatch::TestResponse
def recycle!
# hack to avoid MonitorMixin double-initialize error:
@mon_mutex_owner_object_id = nil
@mon_mutex = nil
initialize
end
end
else
puts "Monkeypatch for ActionController::TestResponse no longer needed"
end
end
================================================
FILE: vendor/assets/javascripts/plugin.js
================================================
(function($) {
$.fn.railsSortable = function(options) {
options = options || {};
var settings = $.extend({}, options);
settings.baseUrl = settings.baseUrl || '';
settings.update = function(event, ui) {
if (typeof options.update === 'function') {
options.update(event, ui);
}
$.ajax({
type: 'POST',
url: settings.baseUrl + '/sortable/reorder',
dataType: 'json',
contentType: 'application/json',
data: JSON.stringify({
rails_sortable: $(this).sortable('toArray'),
}),
});
}
this.sortable(settings);
};
})(jQuery);
================================================
FILE: vendor/assets/javascripts/rails_sortable.js
================================================
//= require_tree .