query_delegator 1.0.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: de7f682e9257edaad5326f54019aa84357b53820af24b60be2d5f920431431b3
4
+ data.tar.gz: 74d9add566f0af6e39d7e867c2928d672fff9e4e1c7718ca9b3f0f069eafeedb
5
+ SHA512:
6
+ metadata.gz: 5d2ef26397dad3c9aadb540cae8b2c5eca5cc57060d0cfa82402d6e83cabe60c53cb2dd12bae41d7d20f1bee8ab88a4c53ba0c5c57cf6e6a9162799de6848928
7
+ data.tar.gz: 8eca6a5e8da0dd14dc201c2a7c7463faba2a596136d59f8879130c34619075d3da55b1618d4ddb82ec63870d7b19e5d99be45b68eaef6360b6205a2a40100472
data/.gitignore ADDED
@@ -0,0 +1,8 @@
1
+ /.bundle/
2
+ /.yardoc
3
+ /_yardoc/
4
+ /coverage/
5
+ /doc/
6
+ /pkg/
7
+ /spec/reports/
8
+ /tmp/
data/.travis.yml ADDED
@@ -0,0 +1,10 @@
1
+ ---
2
+ sudo: false
3
+ language: ruby
4
+ cache: bundler
5
+ rvm:
6
+ - 2.5
7
+ - 2.6
8
+ - 2.7
9
+ - ruby-head
10
+ before_install: gem install bundler
@@ -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 ritchie@richorelse.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,6 @@
1
+ source "https://rubygems.org"
2
+
3
+ git_source(:github) {|repo_name| "https://github.com/#{repo_name}" }
4
+
5
+ # Specify your gem's dependencies in query_delegator.gemspec
6
+ gemspec
data/LICENSE.txt ADDED
@@ -0,0 +1,21 @@
1
+ The MIT License (MIT)
2
+
3
+ Copyright (c) 2021 Ritchie Paul Buitre
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,203 @@
1
+ # QueryDelegator
2
+
3
+ Write composable and table agnostic query objects for Active Record scopes. Move query code from `ActiveRecord` models into query objects, because database query code do not belong in the model.
4
+
5
+ ## Installation
6
+
7
+ QueryDelegator works with Rails 5.1.7 onwards. Add this line to your application's Gemfile:
8
+
9
+ ```ruby
10
+ gem 'query_delegator'
11
+ ```
12
+
13
+ And then execute:
14
+
15
+ $ bundle
16
+
17
+ Or install it yourself as:
18
+
19
+ $ gem install query_delegator
20
+
21
+ ## Usage
22
+
23
+ Query objects inherit from `QueryDelegator` class, they typically live under `app/queries` directory.
24
+ Naming convention suggests adding a `Query` suffix to query object class names.
25
+ Alternatively prefixing class names with words like `By` is shorter and reads more naturally.
26
+
27
+ ```ruby
28
+ class ByEmail < QueryDelegator
29
+ def call(email)
30
+ at(email).first
31
+ end
32
+
33
+ def at(email)
34
+ where(email: email.to_s.downcase)
35
+ end
36
+
37
+ def be(email)
38
+ return all unless email.blank?
39
+
40
+ at email
41
+ end
42
+ end
43
+ ```
44
+
45
+ Wrap scopes outside `ActiveRecord` models, by either passing the scope as an argument when instantiating a query object or
46
+ by passing the query object class as a block argument to the scope's `then` method, also known as `yield_self`.
47
+
48
+ ```ruby
49
+ @user = ByEmail.new(User).("john.doe@example.test")
50
+ @contacts = @user.contacts.then(&ByEmail).be(params[:email])
51
+ ```
52
+
53
+ You may also wrap scopes inside `ActiveRecord` models, like so:
54
+
55
+ ```ruby
56
+ class User < ApplicationRecord
57
+ has_many :contacts
58
+ scope :by_email, ByEmail
59
+ end
60
+
61
+ class Contact < ApplicationRecord
62
+ belong_to :user
63
+ scope :by_email, ByEmail
64
+ end
65
+
66
+ @user = User.by_email.("john.doe@example.test")
67
+ @contacts = @user.contacts.by_email.be(params[:email])
68
+ ```
69
+
70
+ ### QueryDelegator::[]
71
+
72
+ Delegates Active Record scope to a query object method.
73
+ Intended for association and named scopes, it accepts a query object's method name and returns a `Proc`.
74
+
75
+ ```ruby
76
+ class User < ApplicationRecord
77
+ has_many :contacts, ByCreated[:recently]
78
+ scope :since, ByCreated[:since]
79
+ end
80
+
81
+ class ByCreated < QueryDelegator
82
+ def recently
83
+ order(created_at: :desc)
84
+ end
85
+
86
+ def since(timestamp)
87
+ where table[:created_at].gteq(timestamp)
88
+ end
89
+ end
90
+
91
+ @users = User.since 1.year.ago
92
+ ```
93
+
94
+ ### QueryDelegator::Be
95
+
96
+ To add the helper method `be`, include this module in your query object class like so:
97
+
98
+ ```ruby
99
+ class ByPublished < QueryDelegator
100
+ include Be
101
+
102
+ def be_draft
103
+ on nil
104
+ end
105
+
106
+ def be_published
107
+ where.not(published_on: nil)
108
+ end
109
+
110
+ def on(date)
111
+ where(published_on: date)
112
+ end
113
+ end
114
+ ```
115
+
116
+ #### be
117
+
118
+ Given a name, method `be` invokes another method prefixed with `be_`, otherwise
119
+ returns `none` by default or
120
+ returns `all` given a blank name.
121
+
122
+ ```ruby
123
+ @books = @author.books.then(&ByPublished)
124
+ @books.be(['draft']) # returns books without publish date
125
+ @books.be(:published) # returns books with publish date
126
+ @books.be('unknown') # returns none
127
+ @books.be(nil) # returns all books
128
+ ```
129
+
130
+ ### QueryDelegator::MemoryFetching
131
+
132
+ Provides convenient methods intended to retrieve loaded records from memory,
133
+ instead of running queries from the database.
134
+ Include this module in your query object classes like so:
135
+
136
+ ```ruby
137
+ class ByColor < QueryDelegator
138
+ include MemoryFetching
139
+
140
+ def fetch_by_color(color)
141
+ fetch -> { |by| by.color == color }
142
+ end
143
+ end
144
+
145
+ ByEmail.include QueryDelegator::MemoryFetching
146
+ ```
147
+
148
+ #### fetch
149
+
150
+ This helper method retrieves the first record that meets the condition, otherwise
151
+ returns either the given block value or the optional default value which is `nil`.
152
+
153
+ ```ruby
154
+ @vehicles = Vehicle.then(&ByColor)
155
+ @vehicles.fetch_by_color 'red' # returns a red Vehicle record
156
+ @vehicles.fetch(-> v { v.color == 'gold'} # returns nil
157
+ @vehicles.fetch(proc { |v| v.color == 'gold'}, NoVehicle) # returns NoVehicle
158
+ @vehicles.fetch(proc { |v| v.color == 'gold'}) { NoVehicle } # returns NoVehicle
159
+ @vehicles.fetch(Car) # returns a Car record
160
+ ```
161
+
162
+ #### fetch_or_new
163
+
164
+ This method also [fetches](#fetch) a record that meets the condition, otherwise loads a new record with `Hash` from the argument condition.
165
+ Given a block, it instead fetches a record that meets the block condition.
166
+
167
+ ```ruby
168
+ class HasEmailOrPhone < SimpleDelegator
169
+ def ===(contact)
170
+ contact.email == email || contact.phone == phone
171
+ end
172
+
173
+ def to_h
174
+ { full_name: full_name, email: email, phone: phone }
175
+ end
176
+ end
177
+
178
+ @user_contacts = ByEmail.new(@user.contacts)
179
+
180
+ # Returns a Contact with the same customer name or email.
181
+ @customer_contact = @user_contacts.fetch_or_new(HasEmailOrPhone[@customer])
182
+
183
+ # Either fetch primary Contact or load a new Contact with the specified email.
184
+ @primary_contact = @user_contacts.fetch_or_new(email: "john.doe@example.test", &:primary?)
185
+ ```
186
+
187
+ ## Development
188
+
189
+ After checking out the repo, run `bin/setup` to install dependencies. Then, run `rake test` 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
+ ## Contributing
194
+
195
+ Bug reports and pull requests are welcome on GitHub at https://github.com/RichOrElse/query_delegator. 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.
196
+
197
+ ## License
198
+
199
+ The gem is available as open source under the terms of the [MIT License](https://opensource.org/licenses/MIT).
200
+
201
+ ## Code of Conduct
202
+
203
+ Everyone interacting in the QueryDelegator project’s codebases, issue trackers, chat rooms and mailing lists is expected to follow the [code of conduct](https://github.com/RichOrElse/query_delegator/blob/master/CODE_OF_CONDUCT.md).
data/Rakefile ADDED
@@ -0,0 +1,10 @@
1
+ require "bundler/gem_tasks"
2
+ require "rake/testtask"
3
+
4
+ Rake::TestTask.new(:test) do |t|
5
+ t.libs << "test"
6
+ t.libs << "lib"
7
+ t.test_files = FileList["test/**/*_test.rb"]
8
+ end
9
+
10
+ task :default => :test
data/bin/console ADDED
@@ -0,0 +1,14 @@
1
+ #!/usr/bin/env ruby
2
+
3
+ require "bundler/setup"
4
+ require "query_delegator"
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
+
8
+ # Do any other automated setup that you need to do here
@@ -0,0 +1,45 @@
1
+ require "active_support/core_ext/module/delegation"
2
+ require "active_support/core_ext/object"
3
+ require "query_delegator/version"
4
+ require "query_delegator/memory_fetching"
5
+ require "query_delegator/be"
6
+
7
+ class QueryDelegator
8
+ delegate_missing_to :@current_scope
9
+
10
+ def initialize(relation)
11
+ @current_scope = relation.all
12
+ end
13
+
14
+ class << self
15
+ # Returns a Proc which wraps an ActiveRecord scope in a new query object instance.
16
+ def to_proc
17
+ delegator = self
18
+
19
+ proc do |*args|
20
+ if equal? delegator
21
+ new(*args)
22
+ else
23
+ delegator.(self, *args)
24
+ end
25
+ end
26
+ end
27
+
28
+ # Returns a Proc which delegates an ActiveRecord model scope to query object instance method.
29
+ def [](delegating)
30
+ delegator = self
31
+
32
+ if public_instance_method(delegating).arity.zero?
33
+ proc do
34
+ delegator.new(self).public_send delegating
35
+ end
36
+ else
37
+ proc do |*options|
38
+ delegator.new(self).public_send delegating, *options
39
+ end
40
+ end
41
+ end
42
+
43
+ alias_method :call, :new
44
+ end
45
+ end
@@ -0,0 +1,21 @@
1
+ # frozen_string_literal: true
2
+ require_relative 'respond_or_none'
3
+
4
+ class QueryDelegator
5
+ module Be
6
+ using RespondOrNone
7
+
8
+ # Invokes method name prefixed with +be_+, othewise
9
+ # returns +all+ given a blank name or
10
+ # returns +none+ when method is unrecognized.
11
+ def be(name, *args, &blk)
12
+ return all if name.blank?
13
+
14
+ underscored = name.to_s.strip.underscore
15
+ .gsub(/[^0-9a-z _]/i, '')
16
+ .gsub(/\s+/, '_')
17
+
18
+ respond_to("be_#{underscored}", *args, &blk)
19
+ end
20
+ end
21
+ end
@@ -0,0 +1,21 @@
1
+ # frozen_string_literal: true
2
+
3
+ class QueryDelegator
4
+ module MemoryFetching
5
+ # Returns the first record that meets the +condition+, otherwise
6
+ # returns the given +block value+ or
7
+ # returns +nil+ by default unless a second argument is specified.
8
+ def fetch(condition, default_value = nil)
9
+ grep(condition) { |found| return found }
10
+ return yield condition if defined? yield
11
+
12
+ default_value
13
+ end
14
+
15
+ # Returns the first record that meets either the +block condition+ if given or the argument +condition+, otherwise
16
+ # returns a new record with Hash from the argument +condition+.
17
+ def fetch_or_new(condition, &block_condition)
18
+ fetch(block_condition || condition) { new(condition.to_h) }
19
+ end
20
+ end
21
+ end
@@ -0,0 +1,15 @@
1
+ class QueryDelegator
2
+ module RespondOrNone
3
+ # Invokes a public method, otherwise
4
+ # returns +none+ when method is unrecognized
5
+ def respond_to(method_name, *args, &blk)
6
+ return none unless respond_to?(method_name)
7
+
8
+ public_send(method_name, *args, &blk)
9
+ end
10
+
11
+ refine ::Object do
12
+ include RespondOrNone
13
+ end
14
+ end
15
+ end
@@ -0,0 +1,5 @@
1
+ # frozen_string_literal: true
2
+
3
+ class QueryDelegator
4
+ VERSION = "1.0.0"
5
+ end
@@ -0,0 +1,32 @@
1
+
2
+ lib = File.expand_path("../lib", __FILE__)
3
+ $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
4
+ require "query_delegator/version"
5
+
6
+ Gem::Specification.new do |spec|
7
+ spec.name = "query_delegator"
8
+ spec.version = QueryDelegator::VERSION
9
+ spec.authors = ["Ritchie Paul Buitre"]
10
+ spec.email = ["ritchie@richorelse.com"]
11
+
12
+ spec.summary = "Write composable and table agnostic query objects for Active Record scopes."
13
+ spec.description = "Move query code from ActiveRecord models into query objects, because database query code do not belong in the model."
14
+ spec.homepage = "https://github.com/RichOrElse/query_delegator"
15
+ spec.license = "MIT"
16
+
17
+ # Specify which files should be added to the gem when it is released.
18
+ # The `git ls-files -z` loads the files in the RubyGem that have been added into git.
19
+ spec.files = Dir.chdir(File.expand_path('..', __FILE__)) do
20
+ `git ls-files -z`.split("\x0").reject { |f| f.match(%r{^(test|spec|features)/}) }
21
+ end
22
+ spec.bindir = "exe"
23
+ spec.executables = spec.files.grep(%r{^exe/}) { |f| File.basename(f) }
24
+ spec.require_paths = ["lib"]
25
+
26
+ spec.required_ruby_version = ">= 2.2.2"
27
+ spec.add_runtime_dependency "activesupport", ">= 5.1.7"
28
+
29
+ spec.add_development_dependency "bundler", ">= 1.17"
30
+ spec.add_development_dependency "rake", ">= 10.0"
31
+ spec.add_development_dependency "minitest", "~> 5.1"
32
+ end
metadata ADDED
@@ -0,0 +1,115 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: query_delegator
3
+ version: !ruby/object:Gem::Version
4
+ version: 1.0.0
5
+ platform: ruby
6
+ authors:
7
+ - Ritchie Paul Buitre
8
+ autorequire:
9
+ bindir: exe
10
+ cert_chain: []
11
+ date: 2021-03-14 00:00:00.000000000 Z
12
+ dependencies:
13
+ - !ruby/object:Gem::Dependency
14
+ name: activesupport
15
+ requirement: !ruby/object:Gem::Requirement
16
+ requirements:
17
+ - - ">="
18
+ - !ruby/object:Gem::Version
19
+ version: 5.1.7
20
+ type: :runtime
21
+ prerelease: false
22
+ version_requirements: !ruby/object:Gem::Requirement
23
+ requirements:
24
+ - - ">="
25
+ - !ruby/object:Gem::Version
26
+ version: 5.1.7
27
+ - !ruby/object:Gem::Dependency
28
+ name: bundler
29
+ requirement: !ruby/object:Gem::Requirement
30
+ requirements:
31
+ - - ">="
32
+ - !ruby/object:Gem::Version
33
+ version: '1.17'
34
+ type: :development
35
+ prerelease: false
36
+ version_requirements: !ruby/object:Gem::Requirement
37
+ requirements:
38
+ - - ">="
39
+ - !ruby/object:Gem::Version
40
+ version: '1.17'
41
+ - !ruby/object:Gem::Dependency
42
+ name: rake
43
+ requirement: !ruby/object:Gem::Requirement
44
+ requirements:
45
+ - - ">="
46
+ - !ruby/object:Gem::Version
47
+ version: '10.0'
48
+ type: :development
49
+ prerelease: false
50
+ version_requirements: !ruby/object:Gem::Requirement
51
+ requirements:
52
+ - - ">="
53
+ - !ruby/object:Gem::Version
54
+ version: '10.0'
55
+ - !ruby/object:Gem::Dependency
56
+ name: minitest
57
+ requirement: !ruby/object:Gem::Requirement
58
+ requirements:
59
+ - - "~>"
60
+ - !ruby/object:Gem::Version
61
+ version: '5.1'
62
+ type: :development
63
+ prerelease: false
64
+ version_requirements: !ruby/object:Gem::Requirement
65
+ requirements:
66
+ - - "~>"
67
+ - !ruby/object:Gem::Version
68
+ version: '5.1'
69
+ description: Move query code from ActiveRecord models into query objects, because
70
+ database query code do not belong in the model.
71
+ email:
72
+ - ritchie@richorelse.com
73
+ executables: []
74
+ extensions: []
75
+ extra_rdoc_files: []
76
+ files:
77
+ - ".gitignore"
78
+ - ".travis.yml"
79
+ - CODE_OF_CONDUCT.md
80
+ - Gemfile
81
+ - LICENSE.txt
82
+ - README.md
83
+ - Rakefile
84
+ - bin/console
85
+ - bin/setup
86
+ - lib/query_delegator.rb
87
+ - lib/query_delegator/be.rb
88
+ - lib/query_delegator/memory_fetching.rb
89
+ - lib/query_delegator/respond_or_none.rb
90
+ - lib/query_delegator/version.rb
91
+ - query_delegator.gemspec
92
+ homepage: https://github.com/RichOrElse/query_delegator
93
+ licenses:
94
+ - MIT
95
+ metadata: {}
96
+ post_install_message:
97
+ rdoc_options: []
98
+ require_paths:
99
+ - lib
100
+ required_ruby_version: !ruby/object:Gem::Requirement
101
+ requirements:
102
+ - - ">="
103
+ - !ruby/object:Gem::Version
104
+ version: 2.2.2
105
+ required_rubygems_version: !ruby/object:Gem::Requirement
106
+ requirements:
107
+ - - ">="
108
+ - !ruby/object:Gem::Version
109
+ version: '0'
110
+ requirements: []
111
+ rubygems_version: 3.0.3
112
+ signing_key:
113
+ specification_version: 4
114
+ summary: Write composable and table agnostic query objects for Active Record scopes.
115
+ test_files: []