thorderbolt 0.1.1

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.
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA256:
3
+ metadata.gz: b394ea0e7f38af322f018c2818e9dad909fdadde646e59d40d32f38c9235dea7
4
+ data.tar.gz: 3b05e6c6e5bcf79c740ae52eaa353846fb4d933dac1909a447b3e20a5f2f9c7c
5
+ SHA512:
6
+ metadata.gz: 7a12177fcc94fe47cb490b3d31fa5dba722eb053a1a952d38100c38ec04e3f249f75fda6bea11fe8ef1f6bb796ec93a418c1da0e47a78b2dc0b598be9d20dd66
7
+ data.tar.gz: faad95219b4cf2f7b31d753b29c974f01f519198ab7a355337830579403681502c644941bd6ef86134dcc8c7e22c45c1c90fc15fb96410ac26534b85c70a0173
@@ -0,0 +1,12 @@
1
+ /.bundle/
2
+ /.yardoc
3
+ /_yardoc/
4
+ /coverage/
5
+ /doc/
6
+ /pkg/
7
+ /spec/reports/
8
+ /tmp/
9
+ *.gem
10
+
11
+ # rspec failure tracking
12
+ .rspec_status
data/.rspec ADDED
@@ -0,0 +1,3 @@
1
+ --format documentation
2
+ --color
3
+ --require spec_helper
@@ -0,0 +1,39 @@
1
+ require: rubocop-rspec
2
+
3
+ AllCops:
4
+ Exclude:
5
+ - 'vendor/**/*'
6
+ - 'gemfiles/*'
7
+ TargetRubyVersion: 2.6.3
8
+
9
+ RSpec/FilePath:
10
+ Enabled: false
11
+
12
+ RSpec/LetSetup:
13
+ Enabled: false
14
+
15
+ Metrics/BlockLength:
16
+ Exclude:
17
+ - 'spec/**/*.rb'
18
+ - 'thorderbolt.gemspec'
19
+
20
+ Layout/SpaceAroundMethodCallOperator:
21
+ Enabled: true
22
+
23
+ Lint/RaiseException:
24
+ Enabled: true
25
+
26
+ Lint/StructNewOverride:
27
+ Enabled: true
28
+
29
+ Style/ExponentialNotation:
30
+ Enabled: true
31
+
32
+ Style/HashEachMethods:
33
+ Enabled: true
34
+
35
+ Style/HashTransformKeys:
36
+ Enabled: true
37
+
38
+ Style/HashTransformValues:
39
+ Enabled: true
@@ -0,0 +1,18 @@
1
+ language: ruby
2
+ cache: bundler
3
+ rvm:
4
+ - 2.6.3
5
+ before_install: gem install bundler -v 2.1.4
6
+ before_script:
7
+ - curl -L https://codeclimate.com/downloads/test-reporter/test-reporter-latest-linux-amd64 > ./cc-test-reporter
8
+ - chmod +x ./cc-test-reporter
9
+ - ./cc-test-reporter before-build
10
+ script:
11
+ - bundle exec rubocop
12
+ - bundle exec rspec
13
+ after_script:
14
+ - ./cc-test-reporter after-build --exit-code $TRAVIS_TEST_RESULT
15
+ env:
16
+ global:
17
+ - CC_TEST_REPORTER_ID=d6b20efc7dd615c5aecc4a59064bb60903cec8ee59c684698ef084788ca3e463
18
+
@@ -0,0 +1,5 @@
1
+ # Changelog
2
+
3
+ All notable changes to this project will be documented in this file.
4
+
5
+ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/), and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
@@ -0,0 +1,74 @@
1
+ # Contributor Covenant Code of Conduct
2
+
3
+ ## Our Pledge
4
+
5
+ In the interest of fostering an open and welcoming environment, we as
6
+ contributors and maintainers pledge to making participation in our project and
7
+ our community a harassment-free experience for everyone, regardless of age, body
8
+ size, disability, ethnicity, gender identity and expression, level of experience,
9
+ nationality, personal appearance, race, religion, or sexual identity and
10
+ orientation.
11
+
12
+ ## Our Standards
13
+
14
+ Examples of behavior that contributes to creating a positive environment
15
+ include:
16
+
17
+ * Using welcoming and inclusive language
18
+ * Being respectful of differing viewpoints and experiences
19
+ * Gracefully accepting constructive criticism
20
+ * Focusing on what is best for the community
21
+ * Showing empathy towards other community members
22
+
23
+ Examples of unacceptable behavior by participants include:
24
+
25
+ * The use of sexualized language or imagery and unwelcome sexual attention or
26
+ advances
27
+ * Trolling, insulting/derogatory comments, and personal or political attacks
28
+ * Public or private harassment
29
+ * Publishing others' private information, such as a physical or electronic
30
+ address, without explicit permission
31
+ * Other conduct which could reasonably be considered inappropriate in a
32
+ professional setting
33
+
34
+ ## Our Responsibilities
35
+
36
+ Project maintainers are responsible for clarifying the standards of acceptable
37
+ behavior and are expected to take appropriate and fair corrective action in
38
+ response to any instances of unacceptable behavior.
39
+
40
+ Project maintainers have the right and responsibility to remove, edit, or
41
+ reject comments, commits, code, wiki edits, issues, and other contributions
42
+ that are not aligned to this Code of Conduct, or to ban temporarily or
43
+ permanently any contributor for other behaviors that they deem inappropriate,
44
+ threatening, offensive, or harmful.
45
+
46
+ ## Scope
47
+
48
+ This Code of Conduct applies both within project spaces and in public spaces
49
+ when an individual is representing the project or its community. Examples of
50
+ representing a project or community include using an official project e-mail
51
+ address, posting via an official social media account, or acting as an appointed
52
+ representative at an online or offline event. Representation of a project may be
53
+ further defined and clarified by project maintainers.
54
+
55
+ ## Enforcement
56
+
57
+ Instances of abusive, harassing, or otherwise unacceptable behavior may be
58
+ reported by contacting the project team at aleksandr.privorotskiy@gmail.com. All
59
+ complaints will be reviewed and investigated and will result in a response that
60
+ is deemed necessary and appropriate to the circumstances. The project team is
61
+ obligated to maintain confidentiality with regard to the reporter of an incident.
62
+ Further details of specific enforcement policies may be posted separately.
63
+
64
+ Project maintainers who do not follow or enforce the Code of Conduct in good
65
+ faith may face temporary or permanent repercussions as determined by other
66
+ members of the project's leadership.
67
+
68
+ ## Attribution
69
+
70
+ This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4,
71
+ available at [https://contributor-covenant.org/version/1/4][version]
72
+
73
+ [homepage]: https://contributor-covenant.org
74
+ [version]: https://contributor-covenant.org/version/1/4/
data/Gemfile ADDED
@@ -0,0 +1,6 @@
1
+ # frozen_string_literal: true
2
+
3
+ source 'https://rubygems.org'
4
+
5
+ # Specify your gem's dependencies in thorderbolt.gemspec
6
+ gemspec
@@ -0,0 +1,98 @@
1
+ PATH
2
+ remote: .
3
+ specs:
4
+ thorderbolt (0.1.0)
5
+ activerecord (>= 5.0)
6
+
7
+ GEM
8
+ remote: https://rubygems.org/
9
+ specs:
10
+ activemodel (6.0.2.2)
11
+ activesupport (= 6.0.2.2)
12
+ activerecord (6.0.2.2)
13
+ activemodel (= 6.0.2.2)
14
+ activesupport (= 6.0.2.2)
15
+ activesupport (6.0.2.2)
16
+ concurrent-ruby (~> 1.0, >= 1.0.2)
17
+ i18n (>= 0.7, < 2)
18
+ minitest (~> 5.1)
19
+ tzinfo (~> 1.1)
20
+ zeitwerk (~> 2.2)
21
+ ast (2.4.0)
22
+ byebug (11.1.1)
23
+ coderay (1.1.2)
24
+ concurrent-ruby (1.1.6)
25
+ diff-lcs (1.3)
26
+ docile (1.3.2)
27
+ factory_bot (5.1.2)
28
+ activesupport (>= 4.2.0)
29
+ i18n (1.8.2)
30
+ concurrent-ruby (~> 1.0)
31
+ jaro_winkler (1.5.4)
32
+ json (2.3.0)
33
+ method_source (1.0.0)
34
+ minitest (5.14.0)
35
+ parallel (1.19.1)
36
+ parser (2.7.1.1)
37
+ ast (~> 2.4.0)
38
+ pry (0.13.1)
39
+ coderay (~> 1.1)
40
+ method_source (~> 1.0)
41
+ pry-byebug (3.9.0)
42
+ byebug (~> 11.0)
43
+ pry (~> 0.13.0)
44
+ rainbow (3.0.0)
45
+ rexml (3.2.4)
46
+ rspec (3.9.0)
47
+ rspec-core (~> 3.9.0)
48
+ rspec-expectations (~> 3.9.0)
49
+ rspec-mocks (~> 3.9.0)
50
+ rspec-core (3.9.1)
51
+ rspec-support (~> 3.9.1)
52
+ rspec-expectations (3.9.1)
53
+ diff-lcs (>= 1.2.0, < 2.0)
54
+ rspec-support (~> 3.9.0)
55
+ rspec-mocks (3.9.1)
56
+ diff-lcs (>= 1.2.0, < 2.0)
57
+ rspec-support (~> 3.9.0)
58
+ rspec-support (3.9.2)
59
+ rubocop (0.82.0)
60
+ jaro_winkler (~> 1.5.1)
61
+ parallel (~> 1.10)
62
+ parser (>= 2.7.0.1)
63
+ rainbow (>= 2.2.2, < 4.0)
64
+ rexml
65
+ ruby-progressbar (~> 1.7)
66
+ unicode-display_width (>= 1.4.0, < 2.0)
67
+ rubocop-rspec (1.38.1)
68
+ rubocop (>= 0.68.1)
69
+ ruby-progressbar (1.10.1)
70
+ simplecov (0.17.0)
71
+ docile (~> 1.1)
72
+ json (>= 1.8, < 3)
73
+ simplecov-html (~> 0.10.0)
74
+ simplecov-html (0.10.2)
75
+ sqlite3 (1.4.2)
76
+ thread_safe (0.3.6)
77
+ tzinfo (1.2.7)
78
+ thread_safe (~> 0.1)
79
+ unicode-display_width (1.7.0)
80
+ zeitwerk (2.3.0)
81
+
82
+ PLATFORMS
83
+ ruby
84
+
85
+ DEPENDENCIES
86
+ bundler (~> 2.0)
87
+ factory_bot (~> 5.0)
88
+ pry (>= 0.12)
89
+ pry-byebug (~> 3.0)
90
+ rspec (~> 3.0)
91
+ rubocop (~> 0.76)
92
+ rubocop-rspec (~> 1.0)
93
+ simplecov (= 0.17.0)
94
+ sqlite3 (~> 1.4.0)
95
+ thorderbolt!
96
+
97
+ BUNDLED WITH
98
+ 2.1.4
@@ -0,0 +1,21 @@
1
+ The MIT License (MIT)
2
+
3
+ Copyright (c) 2020 Alexandr Privorotskiy
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in
13
+ all copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
21
+ THE SOFTWARE.
@@ -0,0 +1,177 @@
1
+ [![Build Status](https://travis-ci.org/TolichP/thorderbolt.svg?branch=master)](https://travis-ci.org/TolichP/thorderbolt) [![Test Coverage](https://api.codeclimate.com/v1/badges/2a3289492309d6f7740c/test_coverage)](https://codeclimate.com/github/TolichP/thorderbolt/test_coverage) [![Gem Version](https://badge.fury.io/rb/thorderbolt.svg)](https://badge.fury.io/rb/thorderbolt)
2
+
3
+ # Thorderbolt
4
+
5
+ `Thorderbolt` adds the ability to order `ActiveRecord` relation in an arbitrary order without having to store anything extra in the database.
6
+
7
+ It's as easy as:
8
+
9
+ ```ruby
10
+ class User < ActiveRecord::Base
11
+ extend Thorderbolt
12
+ end
13
+
14
+ User.order_as(name: ['John', 'Tom'])
15
+ => #<ActiveRecord::Relation [
16
+ #<User id: 3, name: 'John'>,
17
+ #<User id: 1, name: 'Tom'>,
18
+ #<User id: 2, name: 'Alex'>,
19
+ #<User id: 4, name: 'Mike'>
20
+ #]>
21
+ ```
22
+
23
+ Ordering of each specified field as equal is also supported.
24
+ In that case usual order will be applied for all the satisfying condition records:
25
+
26
+ ```ruby
27
+ User.order_as_any(name: ['John', 'Tom'])
28
+ => #<ActiveRecord::Relation [
29
+ #<User id: 1, name: 'Tom'>,
30
+ #<User id: 3, name: 'John'>,
31
+ #<User id: 2, name: 'Alex'>,
32
+ #<User id: 4, name: 'Mike'>
33
+ #]>
34
+ ```
35
+
36
+ Using `thorderbolt` doesn't require any additional tables in DB.
37
+
38
+ This gem is heavily inspired by [order_as_specified](https://github.com/panorama-ed/order_as_specified), but strongly refactored with addition of some extra features.
39
+
40
+ ## Installation
41
+
42
+ Add this line to your application Gemfile:
43
+
44
+ ```ruby
45
+ gem 'thorderbolt'
46
+ ```
47
+
48
+ And then execute:
49
+
50
+ $ bundle
51
+
52
+ Or install it yourself as:
53
+
54
+ $ gem install thorderbolt
55
+
56
+ ## Usage
57
+
58
+ actually, each example below is true for `order_as` and `order_as_any` methods. The difference is that `order_as` fixes ordering between specified records, when `order_as_any` just puts specified records at the top and don't change ordering between them at all.
59
+
60
+ Basic usage is simple:
61
+
62
+ ```ruby
63
+ class User < ActiveRecord::Base
64
+ extend Thorderbolt
65
+ end
66
+
67
+ User.order_as(name: ['John', 'Tom'])
68
+ => #<ActiveRecord::Relation [
69
+ #<User id: 3, name: 'John'>,
70
+ #<User id: 1, name: 'Tom'>,
71
+ #<User id: 2, name: 'Alex'>,
72
+ #<User id: 4, name: 'Mike'>
73
+ #]>
74
+ ```
75
+
76
+ This returns all `Users` ordered by the given names. Note that this
77
+ ordering is not possible with a simple `ORDER BY`. Magic!
78
+
79
+ Like any other `ActiveRecord` relation, it can be chained:
80
+
81
+ ```ruby
82
+ User
83
+ .where(name: ['John', 'Tom', 'Mike']).
84
+ .order_as(name: ['John', 'Tom'])
85
+ .limit(3)
86
+ => #<ActiveRecord::Relation [
87
+ #<User id: 3, name: 'John'>,
88
+ #<User id: 1, name: 'Tom'>,
89
+ #<User id: 4, name: 'Mike'>
90
+ ]>
91
+ ```
92
+
93
+ We can use chaining in this way to order by multiple attributes as well:
94
+
95
+ ```ruby
96
+ User.
97
+ order_as(name: ['John', 'Mike']).
98
+ order_as(id: [4, 3, 5]).
99
+ order(:updated_at)
100
+ => #<ActiveRecord::Relation [
101
+
102
+ # First is name 'John'...
103
+ #<User id: 1, name: 'John', updated_at: '2020-08-01 02:22:00'>,
104
+
105
+ # Within the name, we order by :updated_at...
106
+ #<User id: 2, name: 'John', updated_at: '2020-08-01 07:29:07'>,
107
+
108
+ # Then name 'Mike'...
109
+ #<User id: 9, name: 'Mike', updated_at: '2020-08-03 04:11:26'>,
110
+
111
+ # Within the name, we order by :updated_at...
112
+ #<User id: 8, name: 'Mike', updated_at: '2020-08-04 18:52:14'>,
113
+
114
+ # Then id 4...
115
+ #<User id: 4, name: 'Alex', updated_at: '2020-08-01 12:59:33'>,
116
+
117
+ # Then id 3...
118
+ #<User id: 3, name: 'Tom', updated_at: '2020-08-02 19:41:44'>,
119
+
120
+ # Then id 5...
121
+ #<User id: 5, name: 'Tom', updated_at: '2020-08-02 22:12:52'>,
122
+
123
+ # Then we order by :updated_at...
124
+ #<User id: 7, name: 'Alex', updated_at: '2020-08-02 14:27:16'>,
125
+ #<User id: 6, name: 'Tom', updated_at: '2020-08-03 14:26:06'>,
126
+ ]>
127
+ ```
128
+
129
+ We can also use this when we want to sort by an attribute in another model:
130
+
131
+ ```ruby
132
+ User
133
+ .joins(:city)
134
+ .order_as(cities: { id: [first_city.id, second_city.id, third_city.id] })
135
+ ```
136
+
137
+ In all the cases, results with attribute values which aren't in tghe given list will be
138
+ sorted as if the attribute is `NULL` in a typical `ORDER BY`:
139
+
140
+ ```ruby
141
+ User.order_as(name: ['Tom', 'John'])
142
+ => #<ActiveRecord::Relation [
143
+ #<User id: 2, name: 'Tom'>,
144
+ #<User id: 3, name: 'John'>,
145
+ #<User id: 1, name: 'Mike'>,
146
+ #<User id: 4, name: 'Mike'>
147
+ ]>
148
+ ```
149
+
150
+ Note that an error is raised if a `nil` value was passed in the ordering params, because
151
+ databases do not have good or consistent support for ordering with `NULL` values
152
+ in an arbitrary order, so this behavior isn't permitted.
153
+
154
+ ## Limitations
155
+
156
+ Databases may have limitations on the underlying number of fields you can have
157
+ in an `ORDER BY` clause. For example, in PostgreSQL if you pass in more than
158
+ 1664 list elements you'll receive such error:
159
+
160
+ ```ruby
161
+ PG::ProgramLimitExceeded: ERROR: target lists can have at most 1664 entries
162
+ ```
163
+ That's a database limitation that this gem cannot avoid, unfortunately.
164
+
165
+ ## Contributing
166
+
167
+ 1. Fork it (https://github.com/TolichP/thorderbolt/fork)
168
+ 2. Create your feature branch (`git checkout -b my-new-feature`)
169
+ 3. Commit your changes (`git commit -am 'Add some feature'`)
170
+ 4. Push to the branch (`git push origin my-new-feature`)
171
+ 5. Create a new Pull Request
172
+
173
+ Please, make sure your changes have appropriate tests (`bundle exec rspec`) and conform to the Rubocop style specified.
174
+
175
+ ## License
176
+
177
+ `Thorderbolt` is released under the [MIT License](https://github.com/TolichP/thorderbolt/blob/master/LICENSE.txt).
@@ -0,0 +1,11 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'bundler/gem_tasks'
4
+ require 'rspec/core/rake_task'
5
+ require 'standalone_migrations'
6
+
7
+ StandaloneMigrations::Tasks.load_tasks
8
+
9
+ RSpec::Core::RakeTask.new(:spec)
10
+
11
+ task default: :spec
@@ -0,0 +1,15 @@
1
+ #!/usr/bin/env ruby
2
+ # frozen_string_literal: true
3
+
4
+ require 'bundler/setup'
5
+ require 'thorderbolt'
6
+
7
+ # You can add fixtures and/or initialization code here to make experimenting
8
+ # with your gem easier. You can also use a different console, if you like.
9
+
10
+ # (If you use this, don't forget to add pry to your Gemfile!)
11
+ # require "pry"
12
+ # Pry.start
13
+
14
+ require 'irb'
15
+ IRB.start(__FILE__)
@@ -0,0 +1,8 @@
1
+ #!/usr/bin/env bash
2
+ set -euo pipefail
3
+ IFS=$'\n\t'
4
+ set -vx
5
+
6
+ bundle install
7
+
8
+ # Do any other automated setup that you need to do here
@@ -0,0 +1,33 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'thorderbolt/version'
4
+ require 'thorderbolt/exceptions'
5
+ require 'thorderbolt/range_builder'
6
+ require 'thorderbolt/params_extractor'
7
+ require 'thorderbolt/base_query_builder'
8
+ require 'thorderbolt/order_query_builder'
9
+ require 'thorderbolt/order_any_query_builder'
10
+
11
+ # Active Record customer ordering
12
+ module Thorderbolt
13
+ def order_as(hash)
14
+ order_with_builder(hash, OrderQueryBuilder)
15
+ end
16
+
17
+ def order_as_any(hash)
18
+ order_with_builder(hash, OrderAnyQueryBuilder)
19
+ end
20
+
21
+ protected
22
+
23
+ def order_with_builder(hash, builder)
24
+ params = ParamsExtractor.call(hash, table_name)
25
+ values = params[:values]
26
+
27
+ return all if params[:values].empty?
28
+ raise ThorderboltError, 'Cannot order by `nil`' if values.any?(&:nil?)
29
+
30
+ builder = builder.new(params)
31
+ order(Arel.sql(builder.build))
32
+ end
33
+ end
@@ -0,0 +1,53 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Thorderbolt
4
+ # Builds full query for performing custom ordering
5
+ class BaseQueryBuilder
6
+ attr_reader :table_name, :attribute, :values
7
+
8
+ def initialize(table_name:, attribute:, values:)
9
+ @table_name = table_name
10
+ @attribute = attribute
11
+ @values = values
12
+ end
13
+
14
+ # result example:
15
+ # CASE
16
+ # WHEN 'cities'.'name'='City 1' THEN 0
17
+ # WHEN 'cities'.'name'='City 5' THEN 1
18
+ # ELSE 2
19
+ # END ASC
20
+ def build
21
+ conditions = build_conditions
22
+ when_queries = build_when_then_part(conditions)
23
+ case_query = build_case_else(when_queries)
24
+ Arel.sql("#{case_query} ASC")
25
+ end
26
+
27
+ protected
28
+
29
+ def build_conditions
30
+ values.map do |value|
31
+ value.is_a?(Range) ? range_equality_part(value) : equality_part(value)
32
+ end
33
+ end
34
+
35
+ # result example:
36
+ # 'cities'.'name'
37
+ def equality_part(value)
38
+ connection = ActiveRecord::Base.connection
39
+ full_column_name = "#{connection.quote_table_name(table_name)}"\
40
+ ".#{connection.quote_column_name(attribute)}"
41
+
42
+ ActiveRecord::Base.sanitize_sql(
43
+ ["#{full_column_name} = :value", value: value]
44
+ )
45
+ end
46
+
47
+ # result example:
48
+ # 'cities'.'population' >= 100 AND 'cities'.'population' < 200
49
+ def range_equality_part(value)
50
+ RangeBuilder.build(table_name, attribute, value)
51
+ end
52
+ end
53
+ end
@@ -0,0 +1,6 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Thorderbolt
4
+ ThorderboltError = Class.new(StandardError)
5
+ ParamsParsingError = Class.new(ThorderboltError)
6
+ end
@@ -0,0 +1,31 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Thorderbolt
4
+ # Builds full query for performing custom ordering
5
+ class OrderAnyQueryBuilder < BaseQueryBuilder
6
+ # result example:
7
+ # CASE
8
+ # WHEN 'cities'.'name'='City 1' OR 'cities'.'name'='City 5'
9
+ # THEN 1
10
+ # ELSE 2
11
+ # END ASC
12
+
13
+ protected
14
+
15
+ # result example:
16
+ # WHEN 'cities'.'name'='City 1' OR 'cities'.'name'='City 2' THEN 0
17
+ def build_when_then_part(conditions)
18
+ "WHEN #{conditions.join(' OR ')} THEN 0"
19
+ end
20
+
21
+ # result example:
22
+ # CASE
23
+ # WHEN 'cities'.'name'='City 1'
24
+ # OR 'cities'.'name'='City 5' THEN 0
25
+ # ELSE 1
26
+ # END
27
+ def build_case_else(when_queries)
28
+ "CASE #{when_queries} ELSE 1 END"
29
+ end
30
+ end
31
+ end
@@ -0,0 +1,33 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Thorderbolt
4
+ # Builds full query for performing custom ordering
5
+ class OrderQueryBuilder < BaseQueryBuilder
6
+ # result example:
7
+ # CASE
8
+ # WHEN 'cities'.'name'='City 1' THEN 0
9
+ # WHEN 'cities'.'name'='City 5' THEN 1
10
+ # ELSE 2
11
+ # END ASC
12
+
13
+ protected
14
+
15
+ # result example:
16
+ # WHEN 'cities'.'name'='City 1' THEN 0
17
+ def build_when_then_part(conditions)
18
+ conditions.map.with_index do |condition, index|
19
+ "WHEN #{condition} THEN #{index}"
20
+ end
21
+ end
22
+
23
+ # result example:
24
+ # CASE
25
+ # WHEN 'cities'.'name'='City 1' THEN 0
26
+ # WHEN 'cities'.'name'='City 5' THEN 1
27
+ # ELSE 2
28
+ # END
29
+ def build_case_else(when_queries)
30
+ "CASE #{when_queries.join(' ')} ELSE #{when_queries.size} END"
31
+ end
32
+ end
33
+ end
@@ -0,0 +1,22 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Thorderbolt
4
+ # Recursively search through the hash to find the last elements:
5
+ # 1. The name of the table we want to condition on
6
+ # 2. The attribute name
7
+ # 3. The attribute values for ordering by.
8
+ class ParamsExtractor
9
+ def self.call(hash, table_name)
10
+ raise ParamsParsingError, 'Could not parse params' unless hash.size == 1
11
+
12
+ key, value = hash.first
13
+ return call(hash[key], key) if value.is_a? Hash
14
+
15
+ {
16
+ table_name: table_name,
17
+ attribute: key,
18
+ values: value
19
+ }
20
+ end
21
+ end
22
+ end
@@ -0,0 +1,29 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Thorderbolt
4
+ # Builds a part of query for using a range as a sorting parameter
5
+ class RangeBuilder
6
+ class << self
7
+ def build(table, column, range)
8
+ full_column_name = "#{connection.quote_table_name(table)}"\
9
+ ".#{connection.quote_column_name(column)}"
10
+
11
+ closing_condition = range.exclude_end? ? '<' : '<='
12
+
13
+ template = "#{full_column_name} >= :minimal "\
14
+ "AND #{full_column_name} #{closing_condition} :maximum"
15
+
16
+ range_bounds = [range.begin, range.end]
17
+ range_hash = { minimal: range_bounds.min, maximum: range_bounds.max }
18
+
19
+ ActiveRecord::Base.sanitize_sql([template, range_hash])
20
+ end
21
+
22
+ protected
23
+
24
+ def connection
25
+ ActiveRecord::Base.connection
26
+ end
27
+ end
28
+ end
29
+ end
@@ -0,0 +1,5 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Thorderbolt
4
+ VERSION = '0.1.1'
5
+ end
@@ -0,0 +1,40 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative 'lib/thorderbolt/version'
4
+
5
+ Gem::Specification.new do |spec|
6
+ spec.name = 'thorderbolt'
7
+ spec.version = Thorderbolt::VERSION
8
+ spec.authors = ['Alexandr Privorotskiy']
9
+ spec.email = ['aleksandr.privorotskiy@gmail.com']
10
+
11
+ spec.summary = 'Active record arbitrary ordering'
12
+ spec.homepage = 'https://github.com/TolichP/thorderbolt'
13
+ spec.license = 'MIT'
14
+ spec.required_ruby_version = Gem::Requirement.new('>= 2.3.0')
15
+
16
+ spec.metadata['homepage_uri'] = spec.homepage
17
+ spec.metadata['source_code_uri'] = 'https://github.com/TolichP/thorderbolt'
18
+ spec.metadata['changelog_uri'] = %(https://github.com/TolichP/thorderbolt/blob/master/CHANGELOG.md)
19
+
20
+ spec.files = Dir.chdir(File.expand_path(__dir__)) do
21
+ `git ls-files -z`.split("\x0").reject do |f|
22
+ f.match(%r{^(test|spec|features)/})
23
+ end
24
+ end
25
+ spec.bindir = 'exe'
26
+ spec.executables = spec.files.grep(%r{^exe/}) { |f| File.basename(f) }
27
+ spec.require_paths = ['lib']
28
+
29
+ spec.add_dependency 'activerecord', '>= 5.0'
30
+
31
+ spec.add_development_dependency 'bundler', '~> 2.0'
32
+ spec.add_development_dependency 'factory_bot', '~> 5.0'
33
+ spec.add_development_dependency 'pry', '>= 0.12'
34
+ spec.add_development_dependency 'pry-byebug', '~> 3.0'
35
+ spec.add_development_dependency 'rspec', '~> 3.0'
36
+ spec.add_development_dependency 'rubocop', '~> 0.76'
37
+ spec.add_development_dependency 'rubocop-rspec', '~> 1.0'
38
+ spec.add_development_dependency 'simplecov', '= 0.17.0'
39
+ spec.add_development_dependency 'sqlite3', '~> 1.4.0'
40
+ end
metadata ADDED
@@ -0,0 +1,208 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: thorderbolt
3
+ version: !ruby/object:Gem::Version
4
+ version: 0.1.1
5
+ platform: ruby
6
+ authors:
7
+ - Alexandr Privorotskiy
8
+ autorequire:
9
+ bindir: exe
10
+ cert_chain: []
11
+ date: 2020-04-23 00:00:00.000000000 Z
12
+ dependencies:
13
+ - !ruby/object:Gem::Dependency
14
+ name: activerecord
15
+ requirement: !ruby/object:Gem::Requirement
16
+ requirements:
17
+ - - ">="
18
+ - !ruby/object:Gem::Version
19
+ version: '5.0'
20
+ type: :runtime
21
+ prerelease: false
22
+ version_requirements: !ruby/object:Gem::Requirement
23
+ requirements:
24
+ - - ">="
25
+ - !ruby/object:Gem::Version
26
+ version: '5.0'
27
+ - !ruby/object:Gem::Dependency
28
+ name: bundler
29
+ requirement: !ruby/object:Gem::Requirement
30
+ requirements:
31
+ - - "~>"
32
+ - !ruby/object:Gem::Version
33
+ version: '2.0'
34
+ type: :development
35
+ prerelease: false
36
+ version_requirements: !ruby/object:Gem::Requirement
37
+ requirements:
38
+ - - "~>"
39
+ - !ruby/object:Gem::Version
40
+ version: '2.0'
41
+ - !ruby/object:Gem::Dependency
42
+ name: factory_bot
43
+ requirement: !ruby/object:Gem::Requirement
44
+ requirements:
45
+ - - "~>"
46
+ - !ruby/object:Gem::Version
47
+ version: '5.0'
48
+ type: :development
49
+ prerelease: false
50
+ version_requirements: !ruby/object:Gem::Requirement
51
+ requirements:
52
+ - - "~>"
53
+ - !ruby/object:Gem::Version
54
+ version: '5.0'
55
+ - !ruby/object:Gem::Dependency
56
+ name: pry
57
+ requirement: !ruby/object:Gem::Requirement
58
+ requirements:
59
+ - - ">="
60
+ - !ruby/object:Gem::Version
61
+ version: '0.12'
62
+ type: :development
63
+ prerelease: false
64
+ version_requirements: !ruby/object:Gem::Requirement
65
+ requirements:
66
+ - - ">="
67
+ - !ruby/object:Gem::Version
68
+ version: '0.12'
69
+ - !ruby/object:Gem::Dependency
70
+ name: pry-byebug
71
+ requirement: !ruby/object:Gem::Requirement
72
+ requirements:
73
+ - - "~>"
74
+ - !ruby/object:Gem::Version
75
+ version: '3.0'
76
+ type: :development
77
+ prerelease: false
78
+ version_requirements: !ruby/object:Gem::Requirement
79
+ requirements:
80
+ - - "~>"
81
+ - !ruby/object:Gem::Version
82
+ version: '3.0'
83
+ - !ruby/object:Gem::Dependency
84
+ name: rspec
85
+ requirement: !ruby/object:Gem::Requirement
86
+ requirements:
87
+ - - "~>"
88
+ - !ruby/object:Gem::Version
89
+ version: '3.0'
90
+ type: :development
91
+ prerelease: false
92
+ version_requirements: !ruby/object:Gem::Requirement
93
+ requirements:
94
+ - - "~>"
95
+ - !ruby/object:Gem::Version
96
+ version: '3.0'
97
+ - !ruby/object:Gem::Dependency
98
+ name: rubocop
99
+ requirement: !ruby/object:Gem::Requirement
100
+ requirements:
101
+ - - "~>"
102
+ - !ruby/object:Gem::Version
103
+ version: '0.76'
104
+ type: :development
105
+ prerelease: false
106
+ version_requirements: !ruby/object:Gem::Requirement
107
+ requirements:
108
+ - - "~>"
109
+ - !ruby/object:Gem::Version
110
+ version: '0.76'
111
+ - !ruby/object:Gem::Dependency
112
+ name: rubocop-rspec
113
+ requirement: !ruby/object:Gem::Requirement
114
+ requirements:
115
+ - - "~>"
116
+ - !ruby/object:Gem::Version
117
+ version: '1.0'
118
+ type: :development
119
+ prerelease: false
120
+ version_requirements: !ruby/object:Gem::Requirement
121
+ requirements:
122
+ - - "~>"
123
+ - !ruby/object:Gem::Version
124
+ version: '1.0'
125
+ - !ruby/object:Gem::Dependency
126
+ name: simplecov
127
+ requirement: !ruby/object:Gem::Requirement
128
+ requirements:
129
+ - - '='
130
+ - !ruby/object:Gem::Version
131
+ version: 0.17.0
132
+ type: :development
133
+ prerelease: false
134
+ version_requirements: !ruby/object:Gem::Requirement
135
+ requirements:
136
+ - - '='
137
+ - !ruby/object:Gem::Version
138
+ version: 0.17.0
139
+ - !ruby/object:Gem::Dependency
140
+ name: sqlite3
141
+ requirement: !ruby/object:Gem::Requirement
142
+ requirements:
143
+ - - "~>"
144
+ - !ruby/object:Gem::Version
145
+ version: 1.4.0
146
+ type: :development
147
+ prerelease: false
148
+ version_requirements: !ruby/object:Gem::Requirement
149
+ requirements:
150
+ - - "~>"
151
+ - !ruby/object:Gem::Version
152
+ version: 1.4.0
153
+ description:
154
+ email:
155
+ - aleksandr.privorotskiy@gmail.com
156
+ executables: []
157
+ extensions: []
158
+ extra_rdoc_files: []
159
+ files:
160
+ - ".gitignore"
161
+ - ".rspec"
162
+ - ".rubocop.yml"
163
+ - ".travis.yml"
164
+ - CHANGELOG.md
165
+ - CODE_OF_CONDUCT.md
166
+ - Gemfile
167
+ - Gemfile.lock
168
+ - LICENSE.txt
169
+ - README.md
170
+ - Rakefile
171
+ - bin/console
172
+ - bin/setup
173
+ - lib/thorderbolt.rb
174
+ - lib/thorderbolt/base_query_builder.rb
175
+ - lib/thorderbolt/exceptions.rb
176
+ - lib/thorderbolt/order_any_query_builder.rb
177
+ - lib/thorderbolt/order_query_builder.rb
178
+ - lib/thorderbolt/params_extractor.rb
179
+ - lib/thorderbolt/range_builder.rb
180
+ - lib/thorderbolt/version.rb
181
+ - thorderbolt.gemspec
182
+ homepage: https://github.com/TolichP/thorderbolt
183
+ licenses:
184
+ - MIT
185
+ metadata:
186
+ homepage_uri: https://github.com/TolichP/thorderbolt
187
+ source_code_uri: https://github.com/TolichP/thorderbolt
188
+ changelog_uri: https://github.com/TolichP/thorderbolt/blob/master/CHANGELOG.md
189
+ post_install_message:
190
+ rdoc_options: []
191
+ require_paths:
192
+ - lib
193
+ required_ruby_version: !ruby/object:Gem::Requirement
194
+ requirements:
195
+ - - ">="
196
+ - !ruby/object:Gem::Version
197
+ version: 2.3.0
198
+ required_rubygems_version: !ruby/object:Gem::Requirement
199
+ requirements:
200
+ - - ">="
201
+ - !ruby/object:Gem::Version
202
+ version: '0'
203
+ requirements: []
204
+ rubygems_version: 3.1.2
205
+ signing_key:
206
+ specification_version: 4
207
+ summary: Active record arbitrary ordering
208
+ test_files: []