filtered 0.1.0

Sign up to get free protection for your applications and to get access to all the features.
checksums.yaml ADDED
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA256:
3
+ metadata.gz: 4d893c9bc84dbc584724e5ebb0e64b6b44a67a0d4b56cbfce897db6ff3ee2b69
4
+ data.tar.gz: 43bc59830b13a4e4ea72e5c540575e312f408f9064beafc341c2f8bd7159189e
5
+ SHA512:
6
+ metadata.gz: 6f80acf6e14e43d402313493c5ca0ec78bd66afbd359782594efbbf3824a39bbc1460f037f17d707b15ce7dc5ae368319388337e0c0d571af7b8c9a60c0c0197
7
+ data.tar.gz: 58a5d0b3fc5da81bac6deda3ce9417e557b7fbb93a1b685a44f91c5b1cb2eb81d340923307b580e1eb4b26263725e44e1c69a14479997117f7937ef65a8c95d7
data/.gitignore ADDED
@@ -0,0 +1,13 @@
1
+ /.bundle/
2
+ /.yardoc
3
+ /_yardoc/
4
+ /coverage/
5
+ /doc/
6
+ /pkg/
7
+ /spec/reports/
8
+ /tmp/
9
+
10
+ # rspec failure tracking
11
+ .rspec_status
12
+ *.gemfile.lock
13
+ .DS_Store
data/.rspec ADDED
@@ -0,0 +1,3 @@
1
+ --format documentation
2
+ --color
3
+ --require spec_helper
data/.travis.yml ADDED
@@ -0,0 +1,53 @@
1
+ ---
2
+ sudo: false
3
+ language: ruby
4
+ cache: bundler
5
+ addons:
6
+ postgresql: "9.6"
7
+ rvm:
8
+ - 2.3.5
9
+ - 2.4.2
10
+ - 2.5.1
11
+ - 2.6.3
12
+ - ruby-head
13
+ - jruby-9.1.9.0
14
+ - jruby-9.2.5.0
15
+ - jruby-head
16
+ gemfile:
17
+ - gemfiles/activerecord_4.0.gemfile
18
+ - gemfiles/activerecord_4.1.gemfile
19
+ - gemfiles/activerecord_4.2.gemfile
20
+ - gemfiles/activerecord_5.0.gemfile
21
+ - gemfiles/activerecord_5.1.gemfile
22
+ - gemfiles/activerecord_5.2.gemfile
23
+ - gemfiles/activerecord_6.0rc1.gemfile
24
+ env:
25
+ - DB=sqlite
26
+ - DB=postgres
27
+
28
+ matrix:
29
+ fast_finish: true
30
+ exclude:
31
+ - rvm: 2.2.6
32
+ gemfile: gemfiles/activerecord_6.0rc1.gemfile
33
+ - rvm: 2.3.5
34
+ gemfile: gemfiles/activerecord_6.0rc1.gemfile
35
+ - rvm: 2.4.2
36
+ gemfile: gemfiles/activerecord_6.0rc1.gemfile
37
+ - rvm: jruby-9.1.9.0
38
+ gemfile: gemfiles/activerecord_5.0.gemfile
39
+ - rvm: jruby-9.1.9.0
40
+ gemfile: gemfiles/activerecord_6.0rc1.gemfile
41
+ - rvm: jruby-9.2.5.0
42
+ gemfile: gemfiles/activerecord_5.0.gemfile
43
+ - rvm: jruby-9.2.5.0
44
+ gemfile: gemfiles/activerecord_6.0rc1.gemfile
45
+ allow_failures:
46
+ - rvm: ruby-head
47
+ - rvm: jruby-head
48
+
49
+ before_install:
50
+ - gem update --system
51
+ - gem install bundler
52
+ script:
53
+ - bundle exec rake
data/Appraisals ADDED
@@ -0,0 +1,112 @@
1
+ appraise "activerecord-6.0rc1" do
2
+ gem "activerecord", "~>6.0.0.rc1", require: "active_record"
3
+ gem "generator_spec"
4
+
5
+ platforms :jruby do
6
+ gem "activerecord-jdbcsqlite3-adapter"
7
+ gem "jdbc-sqlite3"
8
+ gem "jdbc-postgres"
9
+ end
10
+
11
+ platforms :ruby, :mswin, :mingw do
12
+ gem "pg", "~> 1.1.4"
13
+ gem "sqlite3", "~> 1.4.0"
14
+ end
15
+ end
16
+
17
+ appraise "activerecord-5.2" do
18
+ gem "activerecord", "~>5.2", require: "active_record"
19
+ gem "generator_spec"
20
+
21
+ gemfile.platforms :jruby do
22
+ gem "activerecord-jdbcsqlite3-adapter"
23
+ gem "jdbc-sqlite3"
24
+ gem "jdbc-postgres"
25
+ end
26
+
27
+ gemfile.platforms :ruby, :mswin, :mingw do
28
+ gem "sqlite3", "~> 1.3.0"
29
+ gem "pg", "~> 0.21"
30
+ end
31
+ end
32
+
33
+ appraise "activerecord-5.1" do
34
+ gem "activerecord", "~>5.1", require: "active_record"
35
+ gem "generator_spec"
36
+
37
+ gemfile.platforms :jruby do
38
+ gem "activerecord-jdbcsqlite3-adapter"
39
+ gem "jdbc-sqlite3"
40
+ gem "jdbc-postgres"
41
+ end
42
+
43
+ gemfile.platforms :ruby, :mswin, :mingw do
44
+ gem "sqlite3", "~> 1.3.0"
45
+ gem "pg", "~> 0.21"
46
+ end
47
+ end
48
+
49
+ appraise "activerecord-5.0" do
50
+ gem "activerecord", "~>5.0", require: "active_record"
51
+ gem "generator_spec"
52
+
53
+ gemfile.platforms :jruby do
54
+ gem "activerecord-jdbcsqlite3-adapter"
55
+ gem "jdbc-sqlite3"
56
+ gem "jdbc-postgres"
57
+ end
58
+
59
+ gemfile.platforms :ruby, :mswin, :mingw do
60
+ gem "sqlite3", "~> 1.3.0"
61
+ gem "pg", "~> 0.21"
62
+ end
63
+ end
64
+
65
+ appraise "activerecord-4.2" do
66
+ gem "activerecord", "~>4.2", require: "active_record"
67
+ gem "generator_spec"
68
+
69
+ gemfile.platforms :jruby do
70
+ gem "activerecord-jdbcsqlite3-adapter", "~>1.3"
71
+ gem "jdbc-sqlite3"
72
+ gem "jdbc-postgres"
73
+ end
74
+
75
+ gemfile.platforms :ruby, :mswin, :mingw do
76
+ gem "sqlite3", "~> 1.3.0"
77
+ gem "pg", "~> 0.21"
78
+ end
79
+ end
80
+
81
+ appraise "activerecord-4.1" do
82
+ gem "activerecord", "~>4.1", require: "active_record"
83
+ gem "generator_spec"
84
+
85
+ gemfile.platforms :jruby do
86
+ gem "activerecord-jdbcsqlite3-adapter", "~>1.3"
87
+ gem "jdbc-sqlite3"
88
+ gem "jdbc-postgres"
89
+ end
90
+
91
+ gemfile.platforms :ruby, :mswin, :mingw do
92
+ gem "sqlite3", "~> 1.3.0"
93
+ gem "pg", "~> 0.21"
94
+ end
95
+ end
96
+
97
+ appraise "activerecord-4.0" do
98
+ gem "activerecord", "~>4.0", require: "active_record"
99
+ gem "generator_spec"
100
+
101
+ gemfile.platforms :jruby do
102
+ gem "activerecord-jdbcsqlite3-adapter", "~>1.3"
103
+ gem "jdbc-sqlite3"
104
+ gem "jdbc-postgres"
105
+ end
106
+
107
+ gemfile.platforms :ruby, :mswin, :mingw do
108
+ gem "sqlite3", "~> 1.3.0"
109
+ gem "pg", "~> 0.21"
110
+ end
111
+ end
112
+
@@ -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 dubovskoy.a@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 [http://contributor-covenant.org/version/1/4][version]
72
+
73
+ [homepage]: http://contributor-covenant.org
74
+ [version]: http://contributor-covenant.org/version/1/4/
data/Gemfile ADDED
@@ -0,0 +1,4 @@
1
+ source "https://rubygems.org"
2
+
3
+ # Specify your gem's dependencies in filtered.gemspec
4
+ gemspec
data/Gemfile.lock ADDED
@@ -0,0 +1,41 @@
1
+ PATH
2
+ remote: .
3
+ specs:
4
+ filtered (0.1.0)
5
+
6
+ GEM
7
+ remote: https://rubygems.org/
8
+ specs:
9
+ appraisal (2.2.0)
10
+ bundler
11
+ rake
12
+ thor (>= 0.14.0)
13
+ diff-lcs (1.3)
14
+ rake (10.5.0)
15
+ rspec (3.8.0)
16
+ rspec-core (~> 3.8.0)
17
+ rspec-expectations (~> 3.8.0)
18
+ rspec-mocks (~> 3.8.0)
19
+ rspec-core (3.8.0)
20
+ rspec-support (~> 3.8.0)
21
+ rspec-expectations (3.8.3)
22
+ diff-lcs (>= 1.2.0, < 2.0)
23
+ rspec-support (~> 3.8.0)
24
+ rspec-mocks (3.8.0)
25
+ diff-lcs (>= 1.2.0, < 2.0)
26
+ rspec-support (~> 3.8.0)
27
+ rspec-support (3.8.0)
28
+ thor (0.20.3)
29
+
30
+ PLATFORMS
31
+ ruby
32
+
33
+ DEPENDENCIES
34
+ appraisal (~> 2.2)
35
+ bundler (~> 2.0)
36
+ filtered!
37
+ rake (~> 10.0)
38
+ rspec (~> 3.0)
39
+
40
+ BUNDLED WITH
41
+ 2.0.1
data/LICENSE.txt ADDED
@@ -0,0 +1,21 @@
1
+ The MIT License (MIT)
2
+
3
+ Copyright (c) 2019 Alexey Dubovskoy
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.
data/README.md ADDED
@@ -0,0 +1,204 @@
1
+ [![Build Status](https://travis-ci.org/dubadub/filtered.svg?branch=master)](https://travis-ci.org/dubadub/filtered)
2
+
3
+
4
+ # Filtered - add filter to ActiveRecord queries
5
+
6
+ It gives freedom of using any names, columns, scopes or associations behind fields. Also, it allows you to reuse queries or even compose them from reusable parts. Nice part about it is that it ingerates with Rails forms out of the box.
7
+
8
+ ## Installation
9
+
10
+ Add this line to your application's Gemfile:
11
+
12
+ ```ruby
13
+ gem "filtered"
14
+ ```
15
+
16
+ And then run:
17
+
18
+ ```bash
19
+ # 1. Download and install the gem
20
+ $ bundle
21
+
22
+ # 2. Generate a base filter class
23
+ $ rails generate filtered:install
24
+ create app/filters/application_filter.rb
25
+ ```
26
+
27
+ ## Usage
28
+
29
+ To create a new filter with a generator:
30
+
31
+ ```bash
32
+ $ rails generate filter car make model year body # fields can be added later
33
+ create app/filiters/car_filter.rb
34
+ ```
35
+
36
+
37
+ To use this filter in a controller:
38
+
39
+ ```ruby
40
+ # app/controllers/noise_measurements_controller.rb
41
+ class NoiseMeasurementsController < ApplicationController
42
+
43
+ before_action :set_filter
44
+
45
+ def index
46
+ @measurements = CarNoiseMeasurement.all.merge(@filter)
47
+ end
48
+
49
+ private
50
+
51
+ def set_filter
52
+ # it can take an optional block if you need to set an auxilary variable:
53
+ @filter = CarsFilter.new(filter_params) do |f|
54
+ f.user = current_user
55
+ end
56
+ end
57
+
58
+ def filter_params
59
+ params.fetch(:filter, {}).permit(make: [], model: [], year: [], body: [], :ordering)
60
+ end
61
+
62
+ end
63
+ ```
64
+
65
+
66
+ To define your filter:
67
+
68
+ ```ruby
69
+ # app/filters/car_filter.rb
70
+ class CarFilter < ApplicationFilter
71
+ attr_accessor :user
72
+
73
+ # Usage with default values.
74
+
75
+ # It will add a simple `.where(year: ["2010", "2011"])` clause to query.
76
+ field :year
77
+
78
+
79
+ # Or you can fully control how Filtered modifies query with a block.
80
+ # Notice that block returns lambda. That's because we want to postpone
81
+ # it's evaluation and let ActiveRecord do that when required.
82
+
83
+ # It will add `.joins(:specification).merge(Car::Specification.where(year: ["2010", "2011"]))`
84
+ # clause to the query.
85
+ field :year do |year|
86
+ -> { joins(:specification).merge(Car::Specification.where(year: year)) }
87
+ end
88
+
89
+ # There are some options to a filter field.
90
+
91
+ # `allow_nil` (default is false) will allow nil values to be passed into query.
92
+ # Defatul behaviour is to ignore field althogher if value is nil.
93
+ field :year, allow_nil: true
94
+
95
+ # `allow_blank` (default is false) will allow empty values to be passed into query.
96
+ # Defatul behaviour is to ignore field althogher if value is blank.
97
+ field :year, allow_blank: true
98
+
99
+ # `default` will set field default value if field is not passed into constructor.
100
+ # it accepts literal value:
101
+ field :year, default: "2019"
102
+ # method name
103
+ field :year, default: :default_year
104
+ # or lambda with filter object as argument
105
+ field :year, default: -> (filter) { filter.default_year }
106
+
107
+ # `if` and `unless` will switch filter on or off based on value or filter.
108
+ # it can accept lambda with value as argument:
109
+ field :year, if: -> (value) { %w(2018 2019).include?(value) }
110
+ # or value and filter as argument:
111
+ field :year, if: -> (value, filter) { filter.user.present? && %w(2018 2019).include?(value) }
112
+ # or method name. it will pass value as an argument
113
+ field :year, if: :year_applicable?
114
+
115
+ private
116
+
117
+ def default_year
118
+ if user
119
+ user.defaults.year
120
+ else
121
+ "2019"
122
+ end
123
+ end
124
+
125
+ def year_applicable?(value)
126
+ user.present? && %w(2018 2019).include?(value)
127
+ end
128
+
129
+ end
130
+
131
+ ```
132
+
133
+ To use the same `@filter` object in views (it will automatically set all the related inputs in a form):
134
+
135
+ ```
136
+ # app/views/noise_measurements/index.slim
137
+
138
+ = form_for(@filter, url: search_path, method: "GET", as: :filter) do |f|
139
+ .fields
140
+ span Year
141
+ - YEARS.each do |year|
142
+ = year
143
+ = f.check_box :year, { multiple: true }, year, nil
144
+
145
+ .fields
146
+ span Body
147
+ - BODIES.each do |body|
148
+ = body
149
+ = f.check_box :body, { multiple: true }, body, nil
150
+
151
+ .fields
152
+ span Make
153
+ - MAKES.each do |make|
154
+ = make
155
+ = f.check_box :make, { multiple: true }, make, nil
156
+
157
+ .fields
158
+ span Sorting
159
+
160
+ span Year
161
+ = f.radio_button :ordering, "year asc"
162
+ = f.radio_button :ordering, "year desc"
163
+
164
+ span Idle
165
+ = f.radio_button :ordering, "noise_idle asc"
166
+ = f.radio_button :ordering, "noise_idle desc"
167
+ span 50
168
+ = f.radio_button :ordering, "noise_50 asc"
169
+ = f.radio_button :ordering, "noise_50 desc"
170
+ span 80
171
+ = f.radio_button :ordering, "noise_80 asc"
172
+ = f.radio_button :ordering, "noise_80 desc"
173
+
174
+ .actions
175
+ = f.submit "Filter"
176
+ ```
177
+
178
+
179
+ ## Under the hood
180
+
181
+ Filtered uses API provided by ActiveRecord [merge method](https://api.rubyonrails.org/classes/ActiveRecord/SpawnMethods.html#method-i-merge). There are a few open issues in ActiveRecord related to that method, please, have a look through it [here](https://github.com/rails/rails/search?q=activerecord+merge&state=open&type=Issues).
182
+
183
+ ## Credits
184
+
185
+ This gem woudn't exist without original ideas of [@caJaeger](https://github.com/caJaeger).
186
+
187
+ ## Development
188
+
189
+ After checking out the repo, run `bin/setup` to install dependencies. Then, run `rake spec` to run the tests. You can also run `bin/console` for an interactive prompt that will allow you to experiment.
190
+
191
+ To install this gem onto your local machine, run `bundle exec rake install`. To release a new version, update the version number in `version.rb`, and then run `bundle exec rake release`, which will create a git tag for the version, push git commits and tags, and push the `.gem` file to [rubygems.org](https://rubygems.org).
192
+
193
+
194
+ ## Contributing
195
+
196
+ Bug reports and pull requests are welcome on GitHub at https://github.com/dubadub/filtered. This project is intended to be a safe, welcoming space for collaboration, and contributors are expected to adhere to the [Contributor Covenant](http://contributor-covenant.org) code of conduct.
197
+
198
+ ## License
199
+
200
+ The gem is available as open source under the terms of the [MIT License](https://opensource.org/licenses/MIT).
201
+
202
+ ## Code of Conduct
203
+
204
+ Everyone interacting in the Filtered project’s codebases, issue trackers, chat rooms and mailing lists is expected to follow the [code of conduct](https://github.com/dubadub/filtered/blob/master/CODE_OF_CONDUCT.md).
data/Rakefile ADDED
@@ -0,0 +1,6 @@
1
+ require "bundler/gem_tasks"
2
+ require "rspec/core/rake_task"
3
+
4
+ RSpec::Core::RakeTask.new(:spec)
5
+
6
+ task :default => :spec
data/bin/console ADDED
@@ -0,0 +1,14 @@
1
+ #!/usr/bin/env ruby
2
+
3
+ require "bundler/setup"
4
+ require "filtered"
5
+
6
+ # You can add fixtures and/or initialization code here to make experimenting
7
+ # with your gem easier. You can also use a different console, if you like.
8
+
9
+ # (If you use this, don't forget to add pry to your Gemfile!)
10
+ # require "pry"
11
+ # Pry.start
12
+
13
+ require "irb"
14
+ IRB.start(__FILE__)
data/bin/setup ADDED
@@ -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
+ bundle exec appraisal install
8
+ # Do any other automated setup that you need to do here
data/filtered.gemspec ADDED
@@ -0,0 +1,30 @@
1
+
2
+ lib = File.expand_path("../lib", __FILE__)
3
+ $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
4
+ require "filtered/version"
5
+
6
+ Gem::Specification.new do |spec|
7
+ spec.name = "filtered"
8
+ spec.version = Filtered::VERSION
9
+ spec.authors = ["Alexey Dubovskoy"]
10
+ spec.email = ["dubovskoy.a@gmail.com"]
11
+
12
+ spec.summary = %q{Filters ActiveRecord queries in a nice way}
13
+ spec.homepage = "https://github.com/dubadub/filtered"
14
+ spec.license = "MIT"
15
+
16
+ # Specify which files should be added to the gem when it is released.
17
+ # The `git ls-files -z` loads the files in the RubyGem that have been added into git.
18
+ spec.files = Dir.chdir(File.expand_path('..', __FILE__)) do
19
+ `git ls-files -z`.split("\x0").reject { |f| f.match(%r{^(test|spec|features|examples|docs|gemfiles)/}) }
20
+ end
21
+ spec.bindir = "exe"
22
+ spec.executables = spec.files.grep(%r{^exe/}) { |f| File.basename(f) }
23
+ spec.require_paths = ["lib"]
24
+
25
+ spec.add_development_dependency "bundler", "~> 2.0"
26
+ spec.add_development_dependency "rake", "~> 10.0"
27
+ spec.add_development_dependency "rspec", "~> 3.0"
28
+ spec.add_development_dependency "appraisal", "~> 2.2"
29
+
30
+ end
@@ -0,0 +1,250 @@
1
+ module Filtered
2
+ class Base
3
+
4
+ module ClassMethods
5
+ # Defines a field in a filter.
6
+ #
7
+ # When you provide no options, it will by default add a simple `where(year: ["2010", "2011"])`
8
+ # clause to the query.
9
+ #
10
+ # class CarFilter < ApplicationFilter
11
+ #
12
+ # field :year
13
+ #
14
+ # end
15
+ #
16
+ # Or with a block which is passed with the current field value. Note that block must return
17
+ # proc which will be merged in the query:
18
+ #
19
+ # class CarFilter < ApplicationFilter
20
+ #
21
+ # field :year do |value|
22
+ # -> { where(year: "20#{value}") }
23
+ # end
24
+ #
25
+ # end
26
+ #
27
+ # The second argument to a block is filter object itself:
28
+ #
29
+ # class CarFilter < ApplicationFilter
30
+ #
31
+ # attr_accessor :user
32
+ #
33
+ # field :year, allow_blank: true do |value, filter|
34
+ # -> { where(year: value, user: filter.user) }
35
+ # end
36
+ #
37
+ # end
38
+ #
39
+ # Options:
40
+ # * <tt>:default</tt> - Specifies a method (e.g. <tt>default: :default_year</tt>),
41
+ # proc (e.g. <tt>default: Proc.new { |filter| filter.default_year }</tt>)
42
+ # or object (e.g <tt>default: "2012"</tt>) to call to determine default value.
43
+ # It will be called only if the field not passed into filter constructor.
44
+ # * <tt>:allow_nil</tt> - Add the field into query if field value is +nil+.
45
+ # * <tt>:allow_blank</tt> - Add the field into query if the value is blank.
46
+ # * <tt>:if</tt> - Specifies a method or proc to call to determine
47
+ # if the field addition to query should occur (e.g. <tt>if: :allow_year</tt>,
48
+ # or <tt>if: Proc.new { |year| %w(2018 2019).include?(year) }</tt>). The method,
49
+ # or proc should return a +true+ or +false+ value.
50
+ # * <tt>:unless</tt> - Specifies a method or proc to call to determine
51
+ # if the field addition to query should not occur (e.g. <tt>if: :allow_year</tt>,
52
+ # or <tt>if: Proc.new { |year| (1999..2005).include?(year) }</tt>). The method,
53
+ # or proc should return a +true+ or +false+ value.
54
+
55
+ def field(field_name, options = {}, &block)
56
+ field_name = field_name.to_sym
57
+
58
+ field_definition = FieldDefinition.new.tap do |fd|
59
+ fd.query_updater = if block_given?
60
+ # TODO look for methods to validate that block returns proc
61
+ block
62
+ else
63
+ # AR ref
64
+ ->(value) { -> { where(field_name => value) } }
65
+ end
66
+
67
+
68
+ raise Error, "'if' can't be used with 'allow_nil' or 'allow_blank'" if options[:if] && (options[:allow_nil] || options[:allow_blank])
69
+
70
+ fd.acceptance_computer = if options[:if].is_a?(Proc)
71
+ options[:if]
72
+ elsif options[:if].is_a?(Symbol)
73
+ -> (value, filter) { filter.send(options[:if], value) }
74
+ elsif options[:if].nil?
75
+ # TODO checking that value is blank just comparing to empty string is very naive
76
+ ->(value) { (options[:allow_nil] || !value.nil?) && (options[:allow_blank] || value != "") }
77
+ else
78
+ raise Error, "Unsupported argument #{options[:if].class} for 'if'. Pass proc or method name"
79
+ end
80
+
81
+
82
+ raise Error, "'unless' can't be used with 'allow_nil' or 'allow_blank'" if options[:unless] && (options[:allow_nil] || options[:allow_blank])
83
+
84
+ fd.decline_computer = if options[:unless].is_a?(Proc)
85
+ options[:unless]
86
+ elsif options[:unless].is_a?(Symbol)
87
+ -> (value, filter) { filter.send(options[:unless], value) }
88
+ elsif options[:unless].nil?
89
+ -> { false }
90
+ else
91
+ raise Error, "Unsupported argument #{options[:unless].class} for 'unless'. Pass proc or method name"
92
+ end
93
+
94
+
95
+ fd.default_computer = if options[:default].is_a?(Proc)
96
+ options[:default]
97
+ elsif options[:default].is_a?(Symbol)
98
+ -> (filter) { filter.send(options[:default]) }
99
+ elsif options[:default]
100
+ -> (_) { options[:default] }
101
+ end
102
+ end
103
+
104
+ field_definitions[field_name] = field_definition
105
+
106
+ define_method field_name do
107
+ fields[field_name]
108
+ end
109
+ end
110
+
111
+ def field_definitions
112
+ instance_variable_get(:"@field_definitions")
113
+ end
114
+ end
115
+
116
+ module InstanceMehods
117
+ def initialize(*_)
118
+ @field_set = FieldSet.new(self.class.field_definitions)
119
+
120
+ super
121
+ end
122
+
123
+ private
124
+
125
+ def fields
126
+ @field_set
127
+ end
128
+ end
129
+
130
+ extend ClassMethods
131
+ prepend InstanceMehods
132
+
133
+ def self.inherited(base)
134
+ base.instance_variable_set(:"@field_definitions", Hash.new)
135
+
136
+ if field_definitions
137
+ field_definitions.each do |(name, definition)|
138
+ base.field_definitions[name] = definition
139
+ end
140
+ end
141
+
142
+ super
143
+ end
144
+
145
+ # Initializes a new filter with the given +params+.
146
+ #
147
+ #
148
+ # class CarFilter < ApplicationFilter
149
+ #
150
+ # attr_accessor :user
151
+ #
152
+ # field :year, allow_blank: true do |value, filter|
153
+ # -> { where(year: value, user: filter.user) }
154
+ # end
155
+ #
156
+ # field :make
157
+ # field :model
158
+ # field :body
159
+ #
160
+ # end
161
+ #
162
+ # class NoiseMeasurementsController < ApplicationController
163
+ # before_action :set_filter
164
+ #
165
+ # def index
166
+ # @measurements = CarNoiseMeasurement.all.merge(@filter)
167
+ # end
168
+ #
169
+ # private
170
+ #
171
+ # def set_filter
172
+ # @filter = CarsFilter.new(filter_params) do |f|
173
+ # f.user = current_user
174
+ # end
175
+ # end
176
+ #
177
+ # def filter_params
178
+ # params.fetch(:filter, {}).permit(make: [], model: [], year: [], body: [])
179
+ # end
180
+ # end
181
+ def initialize(params = {}, &block)
182
+ params.each do |name, value|
183
+ name = name.to_sym
184
+
185
+ raise Error, "Passing '#{name}' filter which is not defined" unless fields.defined?(name)
186
+
187
+ fields[name] = value
188
+ end
189
+
190
+ yield self if block_given?
191
+ end
192
+
193
+
194
+ # ActiveRecord calls to_proc when filter merged into relation.
195
+ def to_proc
196
+ procs = entitled_fields.inject([]) do |memo, (name, value, definition)|
197
+ memo << eval_option_proc(definition.query_updater, value)
198
+
199
+ memo
200
+ end
201
+
202
+ ->() {
203
+ # here self is an ActiveRecord relation
204
+ procs.inject(self) { |chain, next_proc| chain.merge(next_proc) }
205
+ }
206
+ end
207
+
208
+ def to_hash
209
+ Hash[entitled_fields.map { |name, value| [name, value] }]
210
+ end
211
+
212
+ def inspect
213
+ inspection = entitled_fields.collect { |name, value| "#{name}: #{value.inspect}" }.compact.join(", ")
214
+
215
+ "#<#{self.class} #{inspection}>"
216
+ end
217
+
218
+ private
219
+
220
+ def entitled_fields
221
+ return enum_for(:entitled_fields) unless block_given?
222
+
223
+ fields.each do |name, value, definition|
224
+ value = definition.default_computer.(self) if !value && definition.default_computer
225
+
226
+ value_accepted = eval_option_proc(definition.acceptance_computer, value)
227
+ value_declined = eval_option_proc(definition.decline_computer, value)
228
+
229
+ if value_accepted && !value_declined
230
+ yield name, value, definition
231
+ else
232
+ next
233
+ end
234
+ end
235
+ end
236
+
237
+ def eval_option_proc(proc_, value)
238
+ if proc_.arity == 2
239
+ proc_.call(value, self)
240
+ elsif proc_.arity == 1
241
+ proc_.call(value)
242
+ elsif proc_.arity == 0
243
+ proc_.call()
244
+ else
245
+ raise Error, "Unsupported number of arguments for proc"
246
+ end
247
+ end
248
+
249
+ end
250
+ end
@@ -0,0 +1,5 @@
1
+ module Filtered
2
+ class Engine < ::Rails::Engine
3
+ config.autoload_paths += Dir["#{config.root}/app/filters/**/"]
4
+ end
5
+ end
@@ -0,0 +1,10 @@
1
+ module Filtered
2
+ class FieldDefinition
3
+
4
+ attr_accessor :query_updater,
5
+ :acceptance_computer,
6
+ :decline_computer,
7
+ :default_computer
8
+
9
+ end
10
+ end
@@ -0,0 +1,27 @@
1
+ module Filtered
2
+ class FieldSet
3
+ include Enumerable
4
+
5
+ def initialize(definitions)
6
+ @definitions = definitions
7
+ end
8
+
9
+ def defined?(name)
10
+ !!@definitions[name]
11
+ end
12
+
13
+ def [](name)
14
+ instance_variable_get("@#{name}")
15
+ end
16
+
17
+ def []=(name, value)
18
+ instance_variable_set("@#{name}", value)
19
+ end
20
+
21
+ def each
22
+ @definitions.each do |name, definition|
23
+ yield name, instance_variable_get("@#{name}"), definition
24
+ end
25
+ end
26
+ end
27
+ end
@@ -0,0 +1,3 @@
1
+ module Filtered
2
+ VERSION = "0.1.0"
3
+ end
data/lib/filtered.rb ADDED
@@ -0,0 +1,13 @@
1
+ module Filtered
2
+
3
+ require "filtered/version"
4
+ require "filtered/field_definition"
5
+ require "filtered/field_set"
6
+ require "filtered/base"
7
+
8
+ if defined?(Rails)
9
+ require "filtered/engine"
10
+ end
11
+
12
+ class Error < StandardError; end
13
+ end
@@ -0,0 +1,15 @@
1
+ Description:
2
+ Stubs out a new filter. Pass the filter name, either CamelCased or
3
+ under_scored, and an optional list of fields as arguments.
4
+
5
+ You don't have to think up every field up front, but it helps to
6
+ sketch out a few so you can start working with the filter immediately.
7
+
8
+ To create a filter within a module, specify the filter name as a
9
+ path like 'parent_module/filter_name'.
10
+
11
+ Example:
12
+ `rails generate filter users group persmission`
13
+
14
+ Users filter.
15
+ Filter: app/filters/users_filter.rb
@@ -0,0 +1,17 @@
1
+ class FilterGenerator < Rails::Generators::NamedBase
2
+ check_class_collision suffix: "Filter"
3
+
4
+ source_root File.expand_path("templates", __dir__)
5
+
6
+ argument :fields, type: :array, default: [], banner: "field field"
7
+
8
+ def create_filter_file
9
+ template "filter.rb", File.join("app/filters", class_path, "#{file_name}_filter.rb")
10
+ end
11
+
12
+ private
13
+
14
+ def file_name
15
+ @_file_name ||= super.sub(/_filter\z/i, "")
16
+ end
17
+ end
@@ -0,0 +1,8 @@
1
+ class <%= class_name %>Filter < ApplicationFilter
2
+
3
+ <% for field in fields -%>
4
+ field :<%= field %>
5
+ <% end -%>
6
+
7
+ end
8
+
@@ -0,0 +1,12 @@
1
+ module Filtered
2
+ module Generators
3
+ class InstallGenerator < Rails::Generators::Base
4
+
5
+ source_root File.expand_path("templates", __dir__)
6
+
7
+ def generate_install
8
+ copy_file "application_filter.rb", "app/filters/application_filter.rb"
9
+ end
10
+ end
11
+ end
12
+ end
@@ -0,0 +1,3 @@
1
+ class ApplicationFilter < Filtered::Base
2
+
3
+ end
metadata ADDED
@@ -0,0 +1,123 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: filtered
3
+ version: !ruby/object:Gem::Version
4
+ version: 0.1.0
5
+ platform: ruby
6
+ authors:
7
+ - Alexey Dubovskoy
8
+ autorequire:
9
+ bindir: exe
10
+ cert_chain: []
11
+ date: 2019-06-06 00:00:00.000000000 Z
12
+ dependencies:
13
+ - !ruby/object:Gem::Dependency
14
+ name: bundler
15
+ requirement: !ruby/object:Gem::Requirement
16
+ requirements:
17
+ - - "~>"
18
+ - !ruby/object:Gem::Version
19
+ version: '2.0'
20
+ type: :development
21
+ prerelease: false
22
+ version_requirements: !ruby/object:Gem::Requirement
23
+ requirements:
24
+ - - "~>"
25
+ - !ruby/object:Gem::Version
26
+ version: '2.0'
27
+ - !ruby/object:Gem::Dependency
28
+ name: rake
29
+ requirement: !ruby/object:Gem::Requirement
30
+ requirements:
31
+ - - "~>"
32
+ - !ruby/object:Gem::Version
33
+ version: '10.0'
34
+ type: :development
35
+ prerelease: false
36
+ version_requirements: !ruby/object:Gem::Requirement
37
+ requirements:
38
+ - - "~>"
39
+ - !ruby/object:Gem::Version
40
+ version: '10.0'
41
+ - !ruby/object:Gem::Dependency
42
+ name: rspec
43
+ requirement: !ruby/object:Gem::Requirement
44
+ requirements:
45
+ - - "~>"
46
+ - !ruby/object:Gem::Version
47
+ version: '3.0'
48
+ type: :development
49
+ prerelease: false
50
+ version_requirements: !ruby/object:Gem::Requirement
51
+ requirements:
52
+ - - "~>"
53
+ - !ruby/object:Gem::Version
54
+ version: '3.0'
55
+ - !ruby/object:Gem::Dependency
56
+ name: appraisal
57
+ requirement: !ruby/object:Gem::Requirement
58
+ requirements:
59
+ - - "~>"
60
+ - !ruby/object:Gem::Version
61
+ version: '2.2'
62
+ type: :development
63
+ prerelease: false
64
+ version_requirements: !ruby/object:Gem::Requirement
65
+ requirements:
66
+ - - "~>"
67
+ - !ruby/object:Gem::Version
68
+ version: '2.2'
69
+ description:
70
+ email:
71
+ - dubovskoy.a@gmail.com
72
+ executables: []
73
+ extensions: []
74
+ extra_rdoc_files: []
75
+ files:
76
+ - ".gitignore"
77
+ - ".rspec"
78
+ - ".travis.yml"
79
+ - Appraisals
80
+ - CODE_OF_CONDUCT.md
81
+ - Gemfile
82
+ - Gemfile.lock
83
+ - LICENSE.txt
84
+ - README.md
85
+ - Rakefile
86
+ - bin/console
87
+ - bin/setup
88
+ - filtered.gemspec
89
+ - lib/filtered.rb
90
+ - lib/filtered/base.rb
91
+ - lib/filtered/engine.rb
92
+ - lib/filtered/field_definition.rb
93
+ - lib/filtered/field_set.rb
94
+ - lib/filtered/version.rb
95
+ - lib/generators/filter/USAGE
96
+ - lib/generators/filter/filter_generator.rb
97
+ - lib/generators/filter/templates/filter.rb
98
+ - lib/generators/filtered/install/install_generator.rb
99
+ - lib/generators/filtered/install/templates/application_filter.rb
100
+ homepage: https://github.com/dubadub/filtered
101
+ licenses:
102
+ - MIT
103
+ metadata: {}
104
+ post_install_message:
105
+ rdoc_options: []
106
+ require_paths:
107
+ - lib
108
+ required_ruby_version: !ruby/object:Gem::Requirement
109
+ requirements:
110
+ - - ">="
111
+ - !ruby/object:Gem::Version
112
+ version: '0'
113
+ required_rubygems_version: !ruby/object:Gem::Requirement
114
+ requirements:
115
+ - - ">="
116
+ - !ruby/object:Gem::Version
117
+ version: '0'
118
+ requirements: []
119
+ rubygems_version: 3.0.3
120
+ signing_key:
121
+ specification_version: 4
122
+ summary: Filters ActiveRecord queries in a nice way
123
+ test_files: []