sortability 0.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (51) hide show
  1. checksums.yaml +7 -0
  2. data/MIT-LICENSE +20 -0
  3. data/README.md +2 -0
  4. data/Rakefile +18 -0
  5. data/lib/sortability.rb +6 -0
  6. data/lib/sortability/active_record/base.rb +170 -0
  7. data/lib/sortability/active_record/connection_adapters/table_definition.rb +18 -0
  8. data/lib/sortability/active_record/migration.rb +25 -0
  9. data/lib/sortability/version.rb +3 -0
  10. data/spec/dummy/README.md +4 -0
  11. data/spec/dummy/Rakefile +6 -0
  12. data/spec/dummy/app/assets/javascripts/application.js +13 -0
  13. data/spec/dummy/app/assets/stylesheets/application.css +15 -0
  14. data/spec/dummy/app/controllers/application_controller.rb +5 -0
  15. data/spec/dummy/app/helpers/application_helper.rb +2 -0
  16. data/spec/dummy/app/views/layouts/application.html.erb +14 -0
  17. data/spec/dummy/bin/bundle +3 -0
  18. data/spec/dummy/bin/rails +4 -0
  19. data/spec/dummy/bin/rake +4 -0
  20. data/spec/dummy/config.ru +4 -0
  21. data/spec/dummy/config/application.rb +22 -0
  22. data/spec/dummy/config/boot.rb +5 -0
  23. data/spec/dummy/config/database.yml +25 -0
  24. data/spec/dummy/config/environment.rb +5 -0
  25. data/spec/dummy/config/environments/development.rb +37 -0
  26. data/spec/dummy/config/environments/production.rb +78 -0
  27. data/spec/dummy/config/environments/test.rb +39 -0
  28. data/spec/dummy/config/initializers/assets.rb +8 -0
  29. data/spec/dummy/config/initializers/backtrace_silencers.rb +7 -0
  30. data/spec/dummy/config/initializers/cookies_serializer.rb +3 -0
  31. data/spec/dummy/config/initializers/filter_parameter_logging.rb +4 -0
  32. data/spec/dummy/config/initializers/inflections.rb +16 -0
  33. data/spec/dummy/config/initializers/mime_types.rb +4 -0
  34. data/spec/dummy/config/initializers/session_store.rb +3 -0
  35. data/spec/dummy/config/initializers/wrap_parameters.rb +14 -0
  36. data/spec/dummy/config/locales/en.yml +23 -0
  37. data/spec/dummy/config/routes.rb +56 -0
  38. data/spec/dummy/config/secrets.yml +22 -0
  39. data/spec/dummy/db/test.sqlite3 +0 -0
  40. data/spec/dummy/log/development.log +0 -0
  41. data/spec/dummy/log/test.log +0 -0
  42. data/spec/dummy/public/404.html +67 -0
  43. data/spec/dummy/public/422.html +67 -0
  44. data/spec/dummy/public/500.html +66 -0
  45. data/spec/dummy/public/favicon.ico +0 -0
  46. data/spec/lib/sortability/active_record/base_spec.rb +9 -0
  47. data/spec/lib/sortability/active_record/connection_adapters/table_definition_spec.rb +11 -0
  48. data/spec/lib/sortability/active_record/migration_spec.rb +9 -0
  49. data/spec/rails_helper.rb +51 -0
  50. data/spec/spec_helper.rb +87 -0
  51. metadata +178 -0
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA1:
3
+ metadata.gz: 579a5bb1070dd756f977a6d671a463f18b5481f4
4
+ data.tar.gz: 3dd04eb291ac4bd254ba440e120dee92583fc95d
5
+ SHA512:
6
+ metadata.gz: 08203d0b5ba84d75481b2112d514389c8bec1dec4112b2031065769fd53216bd432c835971b960dc34b961fbcc97daef29fc4eb9dd562966dfd1f406504fe66a
7
+ data.tar.gz: dde8dab18591264e6f229b0f3c5c3a03a92c2e4289ebf4bce1a293a927ac62bdadca7270f4c69b2e3ab2e47f0305c415f1d70bb7944500897ce042ea836705e5
@@ -0,0 +1,20 @@
1
+ Copyright 2014 Rice University
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.
@@ -0,0 +1,2 @@
1
+ sortability
2
+ ===========
@@ -0,0 +1,18 @@
1
+ begin
2
+ require 'bundler/setup'
3
+ rescue LoadError
4
+ puts 'You must `gem install bundler` and `bundle install` to run rake tasks'
5
+ end
6
+
7
+ Bundler::GemHelper.install_tasks
8
+
9
+ require 'rake/testtask'
10
+
11
+ Rake::TestTask.new(:spec) do |t|
12
+ t.libs << 'lib'
13
+ t.libs << 'spec'
14
+ t.pattern = 'spec/**/*_spec.rb'
15
+ t.verbose = false
16
+ end
17
+
18
+ task default: :spec
@@ -0,0 +1,6 @@
1
+ require 'sortability/active_record/base'
2
+ require 'sortability/active_record/connection_adapters/table_definition'
3
+ require 'sortability/active_record/migration'
4
+
5
+ module Sortability
6
+ end
@@ -0,0 +1,170 @@
1
+ module Sortability
2
+ module ActiveRecord
3
+ module Base
4
+ def self.included(base)
5
+ base.extend(ClassMethods)
6
+ end
7
+
8
+ module ClassMethods
9
+ # Defines methods that are used to sort records
10
+ # Use via sortable_belongs_to or sortable_class
11
+ def sortable_methods(options = {})
12
+ on = options[:on] || :sort_position
13
+ container = options[:container]
14
+ inverse_of = options[:inverse_of]
15
+ scope_array = [options[:scope]].flatten.compact
16
+ onname = on.to_s
17
+ setter_mname = "#{onname}="
18
+ peers_mname = "#{onname}_peers"
19
+ before_validation_mname = "#{onname}_before_validation"
20
+ next_by_mname = "next_by_#{onname}"
21
+ prev_by_mname = "prev_by_#{onname}"
22
+ compact_peers_mname = "compact_#{onname}_peers"
23
+
24
+ class_exec do
25
+ before_validation before_validation_mname
26
+
27
+ # Returns all the sort peers for this record, including self
28
+ define_method peers_mname do |force_scope_load = false|
29
+ return send(container).send(inverse_of) \
30
+ unless force_scope_load || container.nil? || inverse_of.nil?
31
+
32
+ relation = self.class.unscoped
33
+ scope_array.each do |s|
34
+ relation = relation.where(s => send(s))
35
+ end
36
+ relation
37
+ end
38
+
39
+ # Assigns the "on" field's value if needed
40
+ # Adds 1 to any conflicting fields
41
+ define_method before_validation_mname do
42
+ val = send(on)
43
+ scope_changed = scope_array.any? { |s|
44
+ !changed_attributes[s].nil? }
45
+
46
+ return unless val.nil? || scope_changed || changes[on]
47
+
48
+ peers = send(peers_mname, scope_changed)
49
+ if val.nil?
50
+ # Assign the next available number to the record
51
+ max_val = (peers.loaded? ? \
52
+ peers.to_a.max_by{|r| r.send(on) || 0}.try(on) : \
53
+ peers.maximum(on)) || 0
54
+ send(setter_mname, max_val + 1)
55
+ elsif peers.to_a.any? { |p| p != self && p.send(on) == val }
56
+ # Make a gap for the record
57
+ peers.where{__send__(on) >= val}.reorder(nil)
58
+ .update_all("#{onname} = - (#{onname} + 1)")
59
+ peers.where{__send__(on) < 0}.reorder(nil)
60
+ .update_all("#{onname} = - #{onname}")
61
+
62
+ # Cause peers to load from the DB the next time they are used
63
+ peers.reset
64
+ end
65
+ end
66
+
67
+ # Gets the next record among the peers
68
+ define_method next_by_mname do
69
+ val = send(on)
70
+ peers = send(peers_mname)
71
+ peers.loaded? ? \
72
+ peers.to_a.detect{|p| p.send(on) > val} : \
73
+ peers.where{__send__(on) > val}.first
74
+ end
75
+
76
+ # Gets the previous record among the peers
77
+ define_method prev_by_mname do
78
+ val = send(on)
79
+ peers = send(peers_mname)
80
+ peers.loaded? ? \
81
+ peers.to_a.reverse.detect{|p| p.send(on) < val} : \
82
+ peers.where{__send__(on) < val}.last
83
+ end
84
+
85
+ # Renumbers the peers so that their numbers are sequential,
86
+ # starting at 1
87
+ define_method compact_peers_mname do
88
+ mysql = \
89
+ defined?(ActiveRecord::ConnectionAdapters::MysqlAdapter) && \
90
+ ActiveRecord::Base.connection.instance_of?(
91
+ ActiveRecord::ConnectionAdapters::MysqlAdapter)
92
+ cend = mysql ? 'END CASE' : 'END'
93
+
94
+ peers = send(peers_mname)
95
+ cases = peers.to_a.collect.with_index do |p, i|
96
+ # Make sure "on" field in self is up to date
97
+ send(setter_mname, i + 1) if p == self
98
+
99
+ "WHEN #{p.send(on)} THEN #{- (i + 1)}"
100
+ end.join(' ')
101
+
102
+ self.class.transaction do
103
+ peers.reorder(nil)
104
+ .update_all("#{onname} = CASE #{onname} #{cases} #{cend}")
105
+ peers.reorder(nil).update_all("#{onname} = - #{onname}")
106
+ end
107
+
108
+ # Mark self as not dirty
109
+ changes_applied
110
+ # Force peers to load from the DB the next time they are used
111
+ peers.reset
112
+ end
113
+ end
114
+ end
115
+
116
+ # Defines a sortable has_many relation on the container
117
+ def sortable_has_many(records, options = {})
118
+ on = options[:on] || :sort_position
119
+
120
+ class_exec do
121
+ has_many records, lambda { order(on) }, options.except(:on)
122
+ end
123
+ end
124
+
125
+ # Defines a sortable belongs_to relation on the child records
126
+ def sortable_belongs_to(container, options = {})
127
+ on = options[:on] || :sort_position
128
+
129
+ class_exec do
130
+ belongs_to container, options.except(:on, :scope)
131
+
132
+ reflection = reflect_on_association(container)
133
+ options[:scope] ||= reflection.polymorphic? ? \
134
+ [reflection.foreign_type,
135
+ reflection.foreign_key] : \
136
+ reflection.foreign_key
137
+ options[:inverse_of] ||= reflection.inverse_of.try(:name)
138
+
139
+ validates on, presence: true,
140
+ numericality: { only_integer: true,
141
+ greater_than: 0 },
142
+ uniqueness: { scope: options[:scope] }
143
+ end
144
+
145
+ options[:container] = container
146
+ sortable_methods(options)
147
+ end
148
+
149
+ # Defines a sortable class without a container
150
+ def sortable_class(options = {})
151
+ on = options[:on] || :sort_position
152
+ scope = options[:scope]
153
+
154
+ class_exec do
155
+ default_scope { order(on) }
156
+
157
+ validates on, presence: true,
158
+ numericality: { only_integer: true,
159
+ greater_than: 0 },
160
+ uniqueness: (scope.nil? ? true : { scope: scope })
161
+ end
162
+
163
+ sortable_methods(options)
164
+ end
165
+ end
166
+ end
167
+ end
168
+ end
169
+
170
+ ActiveRecord::Base.send :include, Sortability::ActiveRecord::Base
@@ -0,0 +1,18 @@
1
+ module Sortability
2
+ module ActiveRecord
3
+ module ConnectionAdapters
4
+ module TableDefinition
5
+ # Adds a non-null sortable column on table creation (no index)
6
+ def sortable(options = {})
7
+ options[:null] = false if options[:null].nil?
8
+ on = options.delete(:on) || :sort_position
9
+
10
+ integer on, options
11
+ end
12
+ end
13
+ end
14
+ end
15
+ end
16
+
17
+ ActiveRecord::ConnectionAdapters::TableDefinition.send(
18
+ :include, Sortability::ActiveRecord::ConnectionAdapters::TableDefinition)
@@ -0,0 +1,25 @@
1
+ module Sortability
2
+ module ActiveRecord
3
+ module Migration
4
+ # Adds a non-null sortable column to an existing table (no index)
5
+ def add_sortable_column(table, options = {})
6
+ options[:null] = false if options[:null].nil?
7
+ on = options.delete(:on) || :sort_position
8
+
9
+ add_column table, on, :integer, options
10
+ end
11
+
12
+ # Adds a unique index covering the sort scope cols in an existing table
13
+ def add_sortable_index(table, options = {})
14
+ options[:unique] = true if options[:unique].nil?
15
+ scope = options.delete(:scope)
16
+ on = options.delete(:on) || :sort_position
17
+ columns = ([scope] << on).flatten.compact
18
+
19
+ add_index table, columns, options
20
+ end
21
+ end
22
+ end
23
+ end
24
+
25
+ ActiveRecord::Migration.send :include, Sortability::ActiveRecord::Migration
@@ -0,0 +1,3 @@
1
+ module Sortability
2
+ VERSION = "0.0.0"
3
+ end
@@ -0,0 +1,4 @@
1
+ Dummy
2
+ -----
3
+
4
+ Dummy application used to test the sortability gem.
@@ -0,0 +1,6 @@
1
+ # Add your own tasks in files placed in lib/tasks ending in .rake,
2
+ # for example lib/tasks/capistrano.rake, and they will automatically be available to Rake.
3
+
4
+ require File.expand_path('../config/application', __FILE__)
5
+
6
+ Rails.application.load_tasks
@@ -0,0 +1,13 @@
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
+ // compiled file.
9
+ //
10
+ // Read Sprockets README (https://github.com/sstephenson/sprockets#sprockets-directives) for details
11
+ // about supported directives.
12
+ //
13
+ //= require_tree .
@@ -0,0 +1,15 @@
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 bottom of the
9
+ * compiled file so the styles you add here take precedence over styles defined in any styles
10
+ * defined in the other CSS/SCSS files in this directory. It is generally better to create a new
11
+ * file per style scope.
12
+ *
13
+ *= require_tree .
14
+ *= require_self
15
+ */
@@ -0,0 +1,5 @@
1
+ class ApplicationController < ActionController::Base
2
+ # Prevent CSRF attacks by raising an exception.
3
+ # For APIs, you may want to use :null_session instead.
4
+ protect_from_forgery with: :exception
5
+ end
@@ -0,0 +1,2 @@
1
+ module ApplicationHelper
2
+ end
@@ -0,0 +1,14 @@
1
+ <!DOCTYPE html>
2
+ <html>
3
+ <head>
4
+ <title>Dummy</title>
5
+ <%= stylesheet_link_tag 'application', media: 'all', 'data-turbolinks-track' => true %>
6
+ <%= javascript_include_tag 'application', 'data-turbolinks-track' => true %>
7
+ <%= csrf_meta_tags %>
8
+ </head>
9
+ <body>
10
+
11
+ <%= yield %>
12
+
13
+ </body>
14
+ </html>
@@ -0,0 +1,3 @@
1
+ #!/usr/bin/env ruby
2
+ ENV['BUNDLE_GEMFILE'] ||= File.expand_path('../../Gemfile', __FILE__)
3
+ load Gem.bin_path('bundler', 'bundle')
@@ -0,0 +1,4 @@
1
+ #!/usr/bin/env ruby
2
+ APP_PATH = File.expand_path('../../config/application', __FILE__)
3
+ require_relative '../config/boot'
4
+ require 'rails/commands'
@@ -0,0 +1,4 @@
1
+ #!/usr/bin/env ruby
2
+ require_relative '../config/boot'
3
+ require 'rake'
4
+ Rake.application.run
@@ -0,0 +1,4 @@
1
+ # This file is used by Rack-based servers to start the application.
2
+
3
+ require ::File.expand_path('../config/environment', __FILE__)
4
+ run Rails.application
@@ -0,0 +1,22 @@
1
+ require File.expand_path('../boot', __FILE__)
2
+
3
+ require 'rails/all'
4
+
5
+ Bundler.require(*Rails.groups)
6
+ require "sortability"
7
+
8
+ module Dummy
9
+ class Application < Rails::Application
10
+ # Settings in config/environments/* take precedence over those specified here.
11
+ # Application configuration should go into files in config/initializers
12
+ # -- all .rb files in that directory are automatically loaded.
13
+
14
+ # Set Time.zone default to the specified zone and make Active Record auto-convert to this zone.
15
+ # Run "rake -D time" for a list of tasks for finding time zone names. Default is UTC.
16
+ # config.time_zone = 'Central Time (US & Canada)'
17
+
18
+ # The default locale is :en and all translations from config/locales/*.rb,yml are auto loaded.
19
+ # config.i18n.load_path += Dir[Rails.root.join('my', 'locales', '*.{rb,yml}').to_s]
20
+ # config.i18n.default_locale = :de
21
+ end
22
+ end
@@ -0,0 +1,5 @@
1
+ # Set up gems listed in the Gemfile.
2
+ ENV['BUNDLE_GEMFILE'] ||= File.expand_path('../../../../Gemfile', __FILE__)
3
+
4
+ require 'bundler/setup' if File.exist?(ENV['BUNDLE_GEMFILE'])
5
+ $LOAD_PATH.unshift File.expand_path('../../../../lib', __FILE__)
@@ -0,0 +1,25 @@
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
+ #
7
+ default: &default
8
+ adapter: sqlite3
9
+ pool: 5
10
+ timeout: 5000
11
+
12
+ development:
13
+ <<: *default
14
+ database: db/development.sqlite3
15
+
16
+ # Warning: The database defined as "test" will be erased and
17
+ # re-generated from your development database when you run "rake".
18
+ # Do not set this db to the same as development or production.
19
+ test:
20
+ <<: *default
21
+ database: db/test.sqlite3
22
+
23
+ production:
24
+ <<: *default
25
+ database: db/production.sqlite3
@@ -0,0 +1,5 @@
1
+ # Load the Rails application.
2
+ require File.expand_path('../application', __FILE__)
3
+
4
+ # Initialize the Rails application.
5
+ Rails.application.initialize!
@@ -0,0 +1,37 @@
1
+ Rails.application.configure do
2
+ # Settings specified here will take precedence over those in config/application.rb.
3
+
4
+ # In the development environment your application's code is reloaded on
5
+ # every request. This slows down response time but is perfect for development
6
+ # since you don't have to restart the web server when you make code changes.
7
+ config.cache_classes = false
8
+
9
+ # Do not eager load code on boot.
10
+ config.eager_load = false
11
+
12
+ # Show full error reports and disable caching.
13
+ config.consider_all_requests_local = true
14
+ config.action_controller.perform_caching = false
15
+
16
+ # Don't care if the mailer can't send.
17
+ config.action_mailer.raise_delivery_errors = false
18
+
19
+ # Print deprecation notices to the Rails logger.
20
+ config.active_support.deprecation = :log
21
+
22
+ # Raise an error on page load if there are pending migrations.
23
+ config.active_record.migration_error = :page_load
24
+
25
+ # Debug mode disables concatenation and preprocessing of assets.
26
+ # This option may cause significant delays in view rendering with a large
27
+ # number of complex assets.
28
+ config.assets.debug = true
29
+
30
+ # Adds additional error checking when serving assets at runtime.
31
+ # Checks for improperly declared sprockets dependencies.
32
+ # Raises helpful error messages.
33
+ config.assets.raise_runtime_errors = true
34
+
35
+ # Raises error for missing translations
36
+ # config.action_view.raise_on_missing_translations = true
37
+ end