the_where 0.1.0

Sign up to get free protection for your applications and to get access to all the features.
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA256:
3
+ metadata.gz: 42e1bbaf99803b72a1c4fa60b671368bc2058d7da23131e919f0ef0f06e6964e
4
+ data.tar.gz: ee258e9d5d1048dc39b532028fe828d623a75cc8ab962e82a898dfe20d91dda4
5
+ SHA512:
6
+ metadata.gz: '088f831bd174328c580ce978f981a5f14fbb02e97f530fda8326219d6ed0b3ed491b9d89f89b1d2ec2fae1a4a7c8a13623f1be7ed10e5c530fac701334c0358d'
7
+ data.tar.gz: '08026322f674724d5fdc38939087c0d3e6589aa2e9cbad710b3fb76ba10959c67476125ad5e559decf3c945cd1aa9837760f54d01e4865be12ee5678f55aa6b5'
@@ -0,0 +1,8 @@
1
+ /.bundle/
2
+ /.yardoc
3
+ /_yardoc/
4
+ /coverage/
5
+ /doc/
6
+ /pkg/
7
+ /spec/reports/
8
+ /tmp/
@@ -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 liuya@163.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
+ source "https://rubygems.org"
2
+
3
+ # Specify your gem's dependencies in the_where.gemspec
4
+ gemspec
5
+
6
+ gem "rake", "~> 12.0"
@@ -0,0 +1,19 @@
1
+ PATH
2
+ remote: .
3
+ specs:
4
+ the_where (0.1.0)
5
+
6
+ GEM
7
+ remote: https://rubygems.org/
8
+ specs:
9
+ rake (12.3.0)
10
+
11
+ PLATFORMS
12
+ ruby
13
+
14
+ DEPENDENCIES
15
+ rake (~> 12.0)
16
+ the_where!
17
+
18
+ BUNDLED WITH
19
+ 2.1.4
@@ -0,0 +1,21 @@
1
+ The MIT License (MIT)
2
+
3
+ Copyright (c) 2020 sai
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,139 @@
1
+ # TheWhere
2
+
3
+ Welcome to your new gem! In this directory, you'll find the files you need to be able to package up your Ruby library into a gem. Put your Ruby code in the file `lib/the_where`. To experiment with that code, run `bin/console` for an interactive prompt.
4
+
5
+ TODO: Delete this and the text above, and describe your gem
6
+
7
+ ## Installation
8
+
9
+ Add this line to your application's Gemfile:
10
+
11
+ ```ruby
12
+ gem 'the_where'
13
+ ```
14
+
15
+ And then execute:
16
+
17
+ $ bundle install
18
+
19
+ Or install it yourself as:
20
+
21
+ $ gem install the_where
22
+
23
+ ## Usage
24
+
25
+ ## TheWhere
26
+
27
+ This Library set default params process for where query in ActiveRecord
28
+
29
+ ## Features and Usage
30
+
31
+ ### Normal equal params
32
+
33
+ - Params:
34
+
35
+ ```ruby
36
+ # rails 4 and later, the_where does nothing
37
+ params = { role_id: 1, age: 20 }
38
+ User.the_where(params)
39
+ ```
40
+
41
+ ### Equal params with association
42
+
43
+ - params
44
+ ```ruby
45
+ User.belongs_to :role
46
+ params = { name: 'dhh', 'role.id': 2 }
47
+
48
+ # you can use any table name or reference name
49
+ params = { name: 'dhh', 'roles.id': 2 }
50
+ ```
51
+ - Before use `the_where`
52
+ ```ruby
53
+ User.includes(:student).where(name: params[:name], role: {id: params[:'role.id']})
54
+ ```
55
+ - After Use `the_where`
56
+ ```ruby
57
+ User.the_where(params)
58
+ ```
59
+
60
+ ### Range params
61
+ - params
62
+ ```ruby
63
+ params = { 'role_id-lte': 2 }
64
+ ```
65
+ - Before use `the_where`
66
+ ```ruby
67
+ User.where('role_id >= ?', params[:'role_id-lte'])
68
+ ```
69
+ - After use `the_where`
70
+ ```ruby
71
+ User.the_where(params)
72
+ ```
73
+
74
+ ### Auto remove blank params by default, no need write query with `if else`
75
+ - params
76
+ ```ruby
77
+ params = { age: '', role_id: 1 }
78
+ ```
79
+
80
+ - Before use `the_where`
81
+ ```ruby
82
+ users = User.where(role_id: params[:role_id])
83
+ users = users.where(age: params[:age]) if params[:age]
84
+ ```
85
+ - After use `the_where`
86
+ ```ruby
87
+ User.the_where(params)
88
+
89
+ # also can control which blank value can use
90
+ User.the_where(params, { allow: [nil] })
91
+ ```
92
+
93
+ ### Order params
94
+ - Params
95
+ ```ruby
96
+ params = { 'age-asc': '1', 'last_login_at-asc': '2' }
97
+ ```
98
+ - Before use `the_where`
99
+ ```ruby
100
+ User.order(age: :asc, last_login_at: :asc)
101
+ ```
102
+ - After use `the_where`
103
+ ```ruby
104
+ User.the_where(params)
105
+ ```
106
+
107
+ ## A sample with all params above
108
+ - Params
109
+ ```ruby
110
+ { name: 'dhh', 'role.id': 2, 'age-lte': 2, 'age-asc': '1', 'last_login_at-asc': '2' }
111
+ ```
112
+ - Before use `the_where`
113
+ ```ruby
114
+ User.includes(:role).where(name: params[:name], 'roles.id': params[:'role.id']).order(age: :asc, last_login_at: :asc)
115
+ ```
116
+ - After use `the_where`
117
+ ```ruby
118
+ User.the_where(params)
119
+ ```
120
+
121
+
122
+ ## Development
123
+
124
+ After checking out the repo, run `bin/setup` to install dependencies. You can also run `bin/console` for an interactive prompt that will allow you to experiment.
125
+
126
+ 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).
127
+
128
+ ## Contributing
129
+
130
+ Bug reports and pull requests are welcome on GitHub at https://github.com/[USERNAME]/the_where. This project is intended to be a safe, welcoming space for collaboration, and contributors are expected to adhere to the [code of conduct](https://github.com/[USERNAME]/the_where/blob/master/CODE_OF_CONDUCT.md).
131
+
132
+
133
+ ## License
134
+
135
+ The gem is available as open source under the terms of the [MIT License](https://opensource.org/licenses/MIT).
136
+
137
+ ## Code of Conduct
138
+
139
+ Everyone interacting in the TheWhere project's codebases, issue trackers, chat rooms and mailing lists is expected to follow the [code of conduct](https://github.com/[USERNAME]/the_where/blob/master/CODE_OF_CONDUCT.md).
@@ -0,0 +1,2 @@
1
+ require "bundler/gem_tasks"
2
+ task :default => :spec
@@ -0,0 +1,14 @@
1
+ #!/usr/bin/env ruby
2
+
3
+ require "bundler/setup"
4
+ require "the_where"
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__)
@@ -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,88 @@
1
+ require 'the_where/not'
2
+ require 'the_where/range'
3
+ require 'the_where/like'
4
+ require 'the_where/order'
5
+
6
+ module TheWhere
7
+ include TheWhere::Not
8
+ include TheWhere::Range
9
+ include TheWhere::Order
10
+ include TheWhere::Like
11
+
12
+ REJECT = ['', ' ', nil]
13
+ STRIP = true
14
+
15
+ def the_where(params = {}, options = {})
16
+ return all if params.blank?
17
+
18
+ params, refs, tables = params_with_table(params, options)
19
+
20
+ range_params = filter_range(params)
21
+ order_params = filter_order(params)
22
+ not_params = filter_not(params)
23
+ like_params = filter_like(params)
24
+
25
+ equal_params = params.except!(*range_params.keys, *order_params.keys, *not_params.keys, *like_params.keys)
26
+
27
+ includes(refs).where(equal_params).references(tables)
28
+ .not_scope(not_params)
29
+ .like_scope(like_params)
30
+ .range_scope(range_params)
31
+ .order_scope(order_params)
32
+ end
33
+
34
+ def params_with_table(params = {}, options = {})
35
+ if options[:reject]
36
+ default_reject = [options[:reject]].flatten
37
+ elsif options[:allow]
38
+ default_reject = REJECT - [options[:allow]].flatten
39
+ else
40
+ default_reject = REJECT
41
+ end
42
+
43
+ unless options.has_key? :strip
44
+ options[:strip] = STRIP
45
+ end
46
+
47
+ params = params.to_h
48
+ params.stringify_keys!
49
+ params.reject! { |_, value| default_reject.include?(value) }
50
+
51
+ refs = []
52
+ tables = []
53
+ final_params = {}
54
+
55
+ params.each do |key, value|
56
+ value = value.strip if value.is_a?(String) && options[:strip]
57
+
58
+ if key =~ /\./
59
+ table, col = key.split('.')
60
+ as_model = reflections[table]
61
+ f_col, _ = col.split('-')
62
+
63
+ if as_model && as_model.klass.column_names.include?(f_col)
64
+ final_params["#{as_model.table_name}.#{col}"] = value
65
+ tables << as_model.table_name
66
+ refs << table.to_sym
67
+ elsif connection.data_sources.include? table
68
+ final_params["#{table}.#{col}"] = value
69
+ tables << table
70
+ keys = reflections.select { |_, v| !v.polymorphic? && v.table_name == table }.keys
71
+ if keys && keys.size == 1
72
+ refs << keys.first.to_sym
73
+ end
74
+ end
75
+ else
76
+ f_key, _ = key.split('-')
77
+ if column_names.include?(f_key)
78
+ final_params["#{table_name}.#{key}"] = value
79
+ end
80
+ end
81
+ end
82
+
83
+ [final_params, refs, tables]
84
+ end
85
+
86
+ end
87
+
88
+ ActiveRecord::Base.extend TheWhere
@@ -0,0 +1,33 @@
1
+ module TheWhere
2
+ module Like
3
+
4
+ def like_scope(params)
5
+ where_string = []
6
+ where_hash = {}
7
+
8
+ params.select{ |k, _| k.end_with?('-like') }.each do |key, value|
9
+ real_key = key.sub(/-like$/, '')
10
+ agent_key = key.gsub(/[-\.]/, '_')
11
+
12
+ where_string << "#{real_key} like :#{agent_key}"
13
+ where_hash.merge! agent_key.to_sym => '%' + value.to_s + '%'
14
+ end
15
+
16
+ where_string = where_string.join ' AND '
17
+
18
+ if where_string.present?
19
+ condition = [where_string, where_hash]
20
+ where(condition)
21
+ else
22
+ all
23
+ end
24
+ end
25
+
26
+ def filter_like(params)
27
+ params.select do |k, _|
28
+ k.end_with?('-like')
29
+ end
30
+ end
31
+
32
+ end
33
+ end
@@ -0,0 +1,26 @@
1
+ module TheWhere
2
+ module Not
3
+
4
+ def not_scope(params)
5
+ where_hash = {}
6
+
7
+ params.each do |key, value|
8
+ real_key = key.sub(/-not$/, '')
9
+ where_hash.merge! real_key.to_sym => value
10
+ end
11
+
12
+ if where_hash.present?
13
+ where.not(where_hash)
14
+ else
15
+ all
16
+ end
17
+ end
18
+
19
+ def filter_not(params)
20
+ params.select do |k, _|
21
+ k.end_with?('-not')
22
+ end
23
+ end
24
+
25
+ end
26
+ end
@@ -0,0 +1,25 @@
1
+ module TheWhere
2
+ module Order
3
+
4
+ def order_scope(params)
5
+ order_array = []
6
+
7
+ params.select{ |key, _| key.end_with?('-asc') }.each do |k, _|
8
+ order_array << k.sub(/-asc$/, ' ASC')
9
+ end
10
+
11
+ params.select{ |key, _| key.end_with?('-desc') }.each do |k, _|
12
+ order_array << k.sub(/-desc$/, ' DESC')
13
+ end
14
+
15
+ order(order_array)
16
+ end
17
+
18
+ def filter_order(params)
19
+ params.select do |k, v|
20
+ k.end_with?('-asc', '-desc') && v =~ /^[1-9]$/
21
+ end
22
+ end
23
+
24
+ end
25
+ end
@@ -0,0 +1,46 @@
1
+ module TheWhere
2
+ module Range
3
+
4
+ PATTERN = {
5
+ '-gt' => '>',
6
+ '-gte' => '>=',
7
+ '-lt' => '<',
8
+ '-lte' => '<='
9
+ }
10
+
11
+ def range_scope(params)
12
+ where_string = []
13
+ where_hash = {}
14
+
15
+ PATTERN.each do |char, sign|
16
+ options = params.select{ |key, _| key.end_with?(char) }
17
+
18
+ options.each do |key, value|
19
+ exp = Regexp.new(char + '$')
20
+ real_key = key.sub(exp, '')
21
+ agent_key = key.gsub(/[-\.]/, '_')
22
+
23
+ where_string << "#{real_key} #{sign} :#{agent_key}"
24
+
25
+ where_hash.merge! agent_key.to_sym => value
26
+ end
27
+ end
28
+
29
+ where_string = where_string.join ' AND '
30
+
31
+ if where_string.present?
32
+ condition = [where_string, where_hash]
33
+ where(condition)
34
+ else
35
+ all
36
+ end
37
+ end
38
+
39
+ def filter_range(params)
40
+ params.select do |k, _|
41
+ k.end_with?(*PATTERN.keys)
42
+ end
43
+ end
44
+
45
+ end
46
+ end
@@ -0,0 +1,3 @@
1
+ module TheWhere
2
+ VERSION = "0.1.0"
3
+ end
@@ -0,0 +1,29 @@
1
+ require_relative 'lib/the_where/version'
2
+
3
+ Gem::Specification.new do |spec|
4
+ spec.name = "the_where"
5
+ spec.version = TheWhere::VERSION
6
+ spec.authors = ["sai1024"]
7
+ spec.email = ["rubyer1993@gmail.com"]
8
+
9
+ spec.summary = "Simpler query for ruby"
10
+ spec.description = "Simpler query for ruby"
11
+ spec.homepage = "https://github.com/sai1024/the_where"
12
+ spec.license = "MIT"
13
+ # spec.required_ruby_version = Gem::Requirement.new(">= 2.3.0")
14
+
15
+ # spec.metadata["allowed_push_host"] = "TODO: Set to 'http://mygemserver.com'"
16
+
17
+ # spec.metadata["homepage_uri"] = spec.homepage
18
+ # spec.metadata["source_code_uri"] = "https://github.com/sai1024/the_where"
19
+ # spec.metadata["changelog_uri"] = "https://github.com/sai1024/the_where/blob/main/README.md"
20
+
21
+ # Specify which files should be added to the gem when it is released.
22
+ # The `git ls-files -z` loads the files in the RubyGem that have been added into git.
23
+ spec.files = Dir.chdir(File.expand_path('..', __FILE__)) do
24
+ `git ls-files -z`.split("\x0").reject { |f| f.match(%r{^(test|spec|features)/}) }
25
+ end
26
+ spec.bindir = "exe"
27
+ spec.executables = spec.files.grep(%r{^exe/}) { |f| File.basename(f) }
28
+ spec.require_paths = ["lib"]
29
+ end
metadata ADDED
@@ -0,0 +1,60 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: the_where
3
+ version: !ruby/object:Gem::Version
4
+ version: 0.1.0
5
+ platform: ruby
6
+ authors:
7
+ - sai1024
8
+ autorequire:
9
+ bindir: exe
10
+ cert_chain: []
11
+ date: 2021-01-06 00:00:00.000000000 Z
12
+ dependencies: []
13
+ description: Simpler query for ruby
14
+ email:
15
+ - rubyer1993@gmail.com
16
+ executables: []
17
+ extensions: []
18
+ extra_rdoc_files: []
19
+ files:
20
+ - ".gitignore"
21
+ - CODE_OF_CONDUCT.md
22
+ - Gemfile
23
+ - Gemfile.lock
24
+ - LICENSE.txt
25
+ - README.md
26
+ - Rakefile
27
+ - bin/console
28
+ - bin/setup
29
+ - lib/the_where.rb
30
+ - lib/the_where/like.rb
31
+ - lib/the_where/not.rb
32
+ - lib/the_where/order.rb
33
+ - lib/the_where/range.rb
34
+ - lib/the_where/version.rb
35
+ - the_where.gemspec
36
+ homepage: https://github.com/sai1024/the_where
37
+ licenses:
38
+ - MIT
39
+ metadata: {}
40
+ post_install_message:
41
+ rdoc_options: []
42
+ require_paths:
43
+ - lib
44
+ required_ruby_version: !ruby/object:Gem::Requirement
45
+ requirements:
46
+ - - ">="
47
+ - !ruby/object:Gem::Version
48
+ version: '0'
49
+ required_rubygems_version: !ruby/object:Gem::Requirement
50
+ requirements:
51
+ - - ">="
52
+ - !ruby/object:Gem::Version
53
+ version: '0'
54
+ requirements: []
55
+ rubyforge_project:
56
+ rubygems_version: 2.7.10
57
+ signing_key:
58
+ specification_version: 4
59
+ summary: Simpler query for ruby
60
+ test_files: []