resource_finder 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA256:
3
+ metadata.gz: 47e024ca2888a84a19f0cc611b14ccb520b90aa17e3a7b1e38d0ee1781be1a9e
4
+ data.tar.gz: 723f623815bf2fb25ffa8eca31ddf77bd5b1721b313467f90a61d15baf35b571
5
+ SHA512:
6
+ metadata.gz: e0638e4ffa8476374aa868e0f84b6c36cbfee546b2b489e08d27edf60e29e48aedce9f798825239ebb81acc8a89964fd84e9890b95815eb6741c85df1553afe4
7
+ data.tar.gz: 3548bd9d1bb1f69c197c90260ea9d0be0a8ae2562a0a4add0ea885aef137ea0d755671a9e3ae8354a101305da5e0115329a1390c51fe67f4879b2102b95ac78c
@@ -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
+ .rubocop.yml
13
+ *.gem
data/.rspec ADDED
@@ -0,0 +1,3 @@
1
+ --format documentation
2
+ --color
3
+ --require spec_helper
@@ -0,0 +1,7 @@
1
+ ---
2
+ sudo: false
3
+ language: ruby
4
+ cache: bundler
5
+ rvm:
6
+ - 2.6.1
7
+ before_install: gem install bundler -v 2.0.1
data/Gemfile ADDED
@@ -0,0 +1,4 @@
1
+ source "https://rubygems.org"
2
+
3
+ # Specify your gem's dependencies in resource_finder.gemspec
4
+ gemspec
@@ -0,0 +1,35 @@
1
+ PATH
2
+ remote: .
3
+ specs:
4
+ resource_finder (0.1.0)
5
+
6
+ GEM
7
+ remote: https://rubygems.org/
8
+ specs:
9
+ diff-lcs (1.3)
10
+ rake (10.5.0)
11
+ rspec (3.8.0)
12
+ rspec-core (~> 3.8.0)
13
+ rspec-expectations (~> 3.8.0)
14
+ rspec-mocks (~> 3.8.0)
15
+ rspec-core (3.8.2)
16
+ rspec-support (~> 3.8.0)
17
+ rspec-expectations (3.8.4)
18
+ diff-lcs (>= 1.2.0, < 2.0)
19
+ rspec-support (~> 3.8.0)
20
+ rspec-mocks (3.8.1)
21
+ diff-lcs (>= 1.2.0, < 2.0)
22
+ rspec-support (~> 3.8.0)
23
+ rspec-support (3.8.2)
24
+
25
+ PLATFORMS
26
+ ruby
27
+
28
+ DEPENDENCIES
29
+ bundler (~> 2.0)
30
+ rake (~> 10.0)
31
+ resource_finder!
32
+ rspec (~> 3.0)
33
+
34
+ BUNDLED WITH
35
+ 2.0.1
@@ -0,0 +1,21 @@
1
+ The MIT License (MIT)
2
+
3
+ Copyright (c) 2019 Charles Koyeung
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,202 @@
1
+ ## ResourceFinder
2
+
3
+ ResourceFinder is a simple Rails gem that finds resource for controller from request parameters. It lets you write less codes and eradicates repeat resource finding codes completely in every controller.
4
+
5
+ ### Purpose
6
+
7
+ Generally, when we need to find the resource in controller for actions, we can do like this:
8
+
9
+ ```ruby
10
+ class UsersController < ApplicationController
11
+
12
+ def show
13
+ @user = User.find(params[:id])
14
+ end
15
+
16
+ def edit
17
+ @user = User.find(params[:id])
18
+ end
19
+
20
+ def update
21
+ @user = User.find(params[:id])
22
+ end
23
+
24
+ def destroy
25
+ @user = User.find(params[:id])
26
+ end
27
+
28
+ end
29
+ ```
30
+
31
+ Or, we always use `before_action` makes it looks better:
32
+
33
+ ```ruby
34
+ class UsersController < ApplicationController
35
+ before_action :find_user, only: [:show, :edit, :update, :destroy]
36
+
37
+ def show
38
+ end
39
+
40
+ def edit
41
+ end
42
+
43
+ def update
44
+ end
45
+
46
+ def destroy
47
+ end
48
+
49
+ private
50
+
51
+ def find_user
52
+ @user = User.find(params[:id])
53
+ end
54
+ end
55
+ ```
56
+
57
+ What we done above can solve the repeate codes problem in a single controller, but there will be a lots of controllers in Rails project, we need to define a lots of `find_xxx` methods in its controller. So ResourceFinder is designed to solve this problem.
58
+
59
+ ### Installation
60
+
61
+ Add the gem to your Gemfile:
62
+
63
+ gem 'resource_finder'
64
+
65
+ Install the gem with bundler:
66
+
67
+ bundle install
68
+
69
+ ### Usage
70
+
71
+ To add ResourceFinder in your Rails project, first put it included in your ApplicationController.
72
+
73
+ ```ruby
74
+ class ApplicationController
75
+ include ResourceFinder
76
+ end
77
+ ```
78
+
79
+ And then you can use it in every controllers which inherited from ApplicationController.
80
+
81
+ ```ruby
82
+ class UsersController < ApplicationController
83
+ findable :user
84
+ end
85
+ ```
86
+
87
+ When nested resources, posts belongs to user.
88
+
89
+ ```ruby
90
+ class PostsController < ApplicationController
91
+ findable :user
92
+ findable :post, scope: :user
93
+ end
94
+ ```
95
+
96
+ ### Configuration
97
+
98
+ Basicly, you can set `only` or `except` options like `before_action`, basides there are some useful keys for options:
99
+
100
+ - model
101
+ - query
102
+ - in
103
+ - of
104
+ - scope
105
+ - lazy
106
+ - silent
107
+
108
+ #### Overriding the default model
109
+
110
+ By default, ResourceFinder will detect model based on the object your set by `findable`.
111
+
112
+ ```ruby
113
+ findable :customer # default Customer model
114
+ findable :customer, model: User
115
+ ```
116
+
117
+ #### Specific the key in parameters as query content in DB
118
+
119
+ By default, ResourceFinder gets the query content by query name `object_id` in parameters.
120
+
121
+ ```ruby
122
+ class PostsController < ApplicationController
123
+ findable :user # params[:user_id]
124
+ end
125
+ ```
126
+
127
+ But if the object model is same as the model deduced from current controller name. ResourceFinder will use `id` to get query content from parameters.
128
+
129
+ ```ruby
130
+ class UsersController < ApplicationController
131
+ findable :user # params[:id]
132
+ findable :customer, model: User # params[:id]
133
+ end
134
+ ```
135
+
136
+ You can also pass a lambda/array/string/symbol to `query` options.
137
+
138
+ ```ruby
139
+ findable :user, query: :uuid # params[:uuid]
140
+ findable :user, query: [:user, :id] # params[:user][:id]
141
+ findable :user, query: -> (params) { your_decoder params[:encode_user_id] }
142
+ ```
143
+
144
+ #### Set query columns for ActiveReord
145
+
146
+ By default, ResourceFinder uses `id` to query.
147
+
148
+ ```ruby
149
+ findable :user # query in column: [:id]
150
+ findable :user, in: :uuid # query in column: [:uuid]
151
+ findable :user, in: [:id, :uuid] # query in columns: [:id, :uuid]
152
+ ```
153
+
154
+ #### Scope limitation
155
+
156
+ For nested resources, maybe you want to limit the resource.
157
+
158
+ ```ruby
159
+ findable :user
160
+ findable :post, scope: :user # make sure @post is one of @user.posts
161
+ ```
162
+
163
+ #### Find resource on an existed resource
164
+
165
+ ```ruby
166
+ findable :user
167
+ findable :city, of: :user # same as: @city = user.city
168
+ ```
169
+
170
+ #### Use it without setting instance variable
171
+
172
+ Sometimes, you prefer to improve performance, `lazy: true` can let ResourceFinder be lazy load, also, there will be no any instance variables generated any more.
173
+
174
+ ```ruby
175
+ class UsersController < ApplicationController
176
+ findable :user, lazy: true
177
+
178
+ def show
179
+ user = findable(:user)
180
+ render json: user
181
+ end
182
+ end
183
+ ```
184
+
185
+ #### Exception silent
186
+
187
+ By default, ResourceFinder will be allowed to raise error during source finding. For example: RecordNotFound. You can set `silent: true` to prevent error raised.
188
+
189
+ ```ruby
190
+ class UsersController < ApplicationController
191
+ findable :user, silent: true
192
+
193
+ def show
194
+ # if user record not found
195
+ # @user will be eq: nil
196
+ end
197
+ end
198
+ ```
199
+
200
+ ### License
201
+
202
+ Released under the [MIT](http://opensource.org/licenses/MIT) license. See LICENSE file for details.
@@ -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
@@ -0,0 +1,14 @@
1
+ #!/usr/bin/env ruby
2
+
3
+ require "bundler/setup"
4
+ require "resource_finder"
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,36 @@
1
+ require "resource_finder/version"
2
+ require "resource_finder/finder"
3
+ require "active_support/concern"
4
+
5
+ # Use Finder
6
+ module ResourceFinder
7
+ extend ActiveSupport::Concern
8
+
9
+ included do
10
+ class_attribute :defined_finders, instance_writer: false, default: {}
11
+ end
12
+
13
+ private
14
+
15
+ def findable(name)
16
+ finder = defined_finders[name]
17
+ finder.call(self, true) if finder
18
+ end
19
+
20
+ def _find_resouces
21
+ defined_finders.each do |name, finder|
22
+ record = finder.call(self)
23
+ instance_variable_set("@#{name}", record) if record
24
+ end
25
+ end
26
+
27
+ # :nodoc:
28
+ module ClassMethods
29
+ def findable(name, options = {})
30
+ _defined_finders = self.defined_finders
31
+ self.defined_finders = _defined_finders.merge(name => Finder.new(name, options))
32
+
33
+ before_action :_find_resouces unless _defined_finders.present?
34
+ end
35
+ end
36
+ end
@@ -0,0 +1,94 @@
1
+ module ResourceFinder
2
+ class Finder
3
+ attr :name, :options
4
+
5
+ def initialize(name, options)
6
+ @name = name.to_s
7
+ @options = options
8
+ end
9
+
10
+ def call(controller, force = false)
11
+ with_controller(controller) do
12
+ check_action(force) do
13
+ find_record
14
+ end
15
+ end
16
+ end
17
+
18
+ def with_controller(controller)
19
+ begin
20
+ @controller = controller
21
+ @params = controller.params
22
+
23
+ yield
24
+ ensure
25
+ remove_instance_variable '@controller'
26
+ remove_instance_variable '@params'
27
+ end
28
+ end
29
+
30
+ def check_action(skip_check)
31
+ return if options[:lazy] && !skip_check
32
+
33
+ action = @params[:action].to_sym
34
+ only_actions = Array.wrap options[:only]
35
+ except_actions = Array.wrap options[:except]
36
+
37
+ if (only_actions.empty? && except_actions.empty?) ||
38
+ (only_actions.present? && only_actions.include?(action)) ||
39
+ (except_actions.present? && except_actions.exclude?(action))
40
+ yield
41
+ end
42
+ end
43
+
44
+ def model
45
+ options[:model] || name.classify.constantize
46
+ end
47
+
48
+ def query
49
+ query_path = options[:query]
50
+
51
+ if query_path.nil?
52
+ ctrl_classify_name = @params[:controller].classify.demodulize
53
+ return model.name == ctrl_classify_name ? @params[:id] : @params["#{name}_id"]
54
+ end
55
+
56
+ case query_path
57
+ when Proc
58
+ query_path.call(@params)
59
+ when Array
60
+ @params.dig(*query_path)
61
+ when String, Symbol
62
+ @params[query_path]
63
+ end
64
+ end
65
+
66
+ def refer(finder_name)
67
+ @controller.instance_variable_get("@#{finder_name}") || @controller.send(:findable, finder_name)
68
+ end
69
+
70
+ def find_record
71
+ if options[:of]
72
+ parent = refer options[:of]
73
+ return parent.try(name)
74
+ end
75
+
76
+ columns = Array.wrap options[:in] || :id
77
+ sql = columns.map { |column| "#{column} = :value" }.join(' OR ')
78
+
79
+ relation = if options[:scope]
80
+ scope = refer options[:scope]
81
+ reflection = scope._reflections.detect do |key, _reflection|
82
+ _reflection.class_name == model.name || key == name.pluralize
83
+ end
84
+ scope.try(reflection.first)
85
+ else
86
+ model
87
+ end
88
+
89
+ relation.find_by!([sql, value: query])
90
+ rescue => e
91
+ raise e unless options[:silent]
92
+ end
93
+ end
94
+ end
@@ -0,0 +1,3 @@
1
+ module ResourceFinder
2
+ VERSION = "0.1.0"
3
+ end
@@ -0,0 +1,29 @@
1
+
2
+ lib = File.expand_path("../lib", __FILE__)
3
+ $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
4
+ require "resource_finder/version"
5
+
6
+ Gem::Specification.new do |spec|
7
+ spec.name = "resource_finder"
8
+ spec.version = ResourceFinder::VERSION
9
+ spec.authors = ["Charles Koyeung"]
10
+ spec.email = ["cenxky@gmail.com"]
11
+
12
+ spec.summary = "Find resource from parameters for controller in an easy way."
13
+ spec.description = "Find resource from parameters for controller in an easy way."
14
+ spec.homepage = "https://github.com/cenxky/resource_finder"
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.add_development_dependency "bundler", "~> 2.0"
27
+ spec.add_development_dependency "rake", "~> 10.0"
28
+ spec.add_development_dependency "rspec", "~> 3.0"
29
+ end
metadata ADDED
@@ -0,0 +1,99 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: resource_finder
3
+ version: !ruby/object:Gem::Version
4
+ version: 0.1.0
5
+ platform: ruby
6
+ authors:
7
+ - Charles Koyeung
8
+ autorequire:
9
+ bindir: exe
10
+ cert_chain: []
11
+ date: 2019-08-03 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
+ description: Find resource from parameters for controller in an easy way.
56
+ email:
57
+ - cenxky@gmail.com
58
+ executables: []
59
+ extensions: []
60
+ extra_rdoc_files: []
61
+ files:
62
+ - ".gitignore"
63
+ - ".rspec"
64
+ - ".travis.yml"
65
+ - Gemfile
66
+ - Gemfile.lock
67
+ - LICENSE.txt
68
+ - README.md
69
+ - Rakefile
70
+ - bin/console
71
+ - bin/setup
72
+ - lib/resource_finder.rb
73
+ - lib/resource_finder/finder.rb
74
+ - lib/resource_finder/version.rb
75
+ - resource_finder.gemspec
76
+ homepage: https://github.com/cenxky/resource_finder
77
+ licenses:
78
+ - MIT
79
+ metadata: {}
80
+ post_install_message:
81
+ rdoc_options: []
82
+ require_paths:
83
+ - lib
84
+ required_ruby_version: !ruby/object:Gem::Requirement
85
+ requirements:
86
+ - - ">="
87
+ - !ruby/object:Gem::Version
88
+ version: '0'
89
+ required_rubygems_version: !ruby/object:Gem::Requirement
90
+ requirements:
91
+ - - ">="
92
+ - !ruby/object:Gem::Version
93
+ version: '0'
94
+ requirements: []
95
+ rubygems_version: 3.0.3
96
+ signing_key:
97
+ specification_version: 4
98
+ summary: Find resource from parameters for controller in an easy way.
99
+ test_files: []