snfoil-context 0.0.1

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: 96734bc3c562904649028a48af86b3bfce1c6afd8273bdf5112dd5e5d608013c
4
+ data.tar.gz: c380bc1234066ff9d29d6f969214b9d72a57f713ff98a11d64cf969e5310ee02
5
+ SHA512:
6
+ metadata.gz: e6c4262868a512ea479115a6dc709425d7e264b9fbebaabab3134e299ced2e7b089833573d109627e670cffe2edd17cc92ffb9ff19e00f4341bf902b9cdb69e5
7
+ data.tar.gz: f9eb6db011db1d21437e95c6881a89b9e361310a16952cccf7a57b58ed6342533643622b6379a2eae1cc8a5ab2413a6e69228308cde9b0e58a6ef98da0cd2710
@@ -0,0 +1,46 @@
1
+ name: build
2
+ on:
3
+ push:
4
+ branches: [ main ]
5
+ pull_request:
6
+
7
+ jobs:
8
+ test:
9
+
10
+ runs-on: ubuntu-latest
11
+
12
+ strategy:
13
+ matrix:
14
+ ruby-version: [2.7, 2.6, 2.5]
15
+
16
+ steps:
17
+ - uses: actions/checkout@v2
18
+ - name: Set up Ruby ${{ matrix.ruby-version }}
19
+ uses: ruby/setup-ruby@v1.81.0
20
+ with:
21
+ ruby-version: ${{ matrix.ruby-version }}
22
+ bundler-cache: true
23
+ - name: Install dependencies
24
+ run: bundle install
25
+ - name: Run tests
26
+ run: bundle exec rspec
27
+ lint:
28
+
29
+ runs-on: ubuntu-latest
30
+
31
+ strategy:
32
+ matrix:
33
+ ruby-version: [2.7, 2.6, 2.5, '3.0']
34
+
35
+ steps:
36
+ - uses: actions/checkout@v2
37
+ - name: Set up Ruby ${{ matrix.ruby-version }}
38
+ uses: ruby/setup-ruby@v1.81.0
39
+ with:
40
+ ruby-version: ${{ matrix.ruby-version }}
41
+ bundler-cache: true
42
+ - name: Install dependencies
43
+ run: bundle install
44
+ - name: Run rubocop
45
+ run: bundle exec rubocop
46
+
data/.gitignore ADDED
@@ -0,0 +1,14 @@
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
+
13
+ # GEMFILE
14
+ Gemfile.lock
data/.rspec ADDED
@@ -0,0 +1,3 @@
1
+ --format documentation
2
+ --color
3
+ --require spec_helper
data/.rubocop.yml ADDED
@@ -0,0 +1,39 @@
1
+ require:
2
+ - rubocop-performance
3
+ - rubocop-rspec
4
+
5
+ AllCops:
6
+ NewCops: enable
7
+ SuggestExtensions: false
8
+ TargetRubyVersion: 2.5.0
9
+
10
+ # ================ LAYOUT ==============
11
+ Layout/LineLength:
12
+ Max: 150
13
+
14
+ # ================ LINT ================
15
+ Lint/AmbiguousBlockAssociation:
16
+ Exclude:
17
+ - spec/**/*_spec.rb
18
+
19
+ Lint/EmptyClass:
20
+ Exclude:
21
+ - spec/**/*_spec.rb
22
+
23
+ # ================ Metics ================
24
+ Metrics/BlockLength:
25
+ Exclude:
26
+ - spec/**/*_spec.rb
27
+
28
+ # ================ RSPEC ================
29
+ RSpec/FilePath:
30
+ Enabled: false
31
+
32
+ RSpec/MultipleExpectations:
33
+ Max: 5
34
+
35
+ RSpec/MultipleMemoizedHelpers:
36
+ Enabled: false
37
+
38
+ RSpec/NestedGroups:
39
+ Max: 5
data/CHANGELOG.md ADDED
@@ -0,0 +1,5 @@
1
+ ## [Unreleased]
2
+
3
+ ## [0.1.0] - 2021-09-26
4
+
5
+ - Initial release
@@ -0,0 +1,84 @@
1
+ # Contributor Covenant Code of Conduct
2
+
3
+ ## Our Pledge
4
+
5
+ We as members, contributors, and leaders pledge to make participation in our community a harassment-free experience for everyone, regardless of age, body size, visible or invisible disability, ethnicity, sex characteristics, gender identity and expression, level of experience, education, socio-economic status, nationality, personal appearance, race, religion, or sexual identity and orientation.
6
+
7
+ We pledge to act and interact in ways that contribute to an open, welcoming, diverse, inclusive, and healthy community.
8
+
9
+ ## Our Standards
10
+
11
+ Examples of behavior that contributes to a positive environment for our community include:
12
+
13
+ * Demonstrating empathy and kindness toward other people
14
+ * Being respectful of differing opinions, viewpoints, and experiences
15
+ * Giving and gracefully accepting constructive feedback
16
+ * Accepting responsibility and apologizing to those affected by our mistakes, and learning from the experience
17
+ * Focusing on what is best not just for us as individuals, but for the overall community
18
+
19
+ Examples of unacceptable behavior include:
20
+
21
+ * The use of sexualized language or imagery, and sexual attention or
22
+ advances of any kind
23
+ * Trolling, insulting or derogatory comments, and personal or political attacks
24
+ * Public or private harassment
25
+ * Publishing others' private information, such as a physical or email
26
+ address, without their explicit permission
27
+ * Other conduct which could reasonably be considered inappropriate in a
28
+ professional setting
29
+
30
+ ## Enforcement Responsibilities
31
+
32
+ Community leaders are responsible for clarifying and enforcing our standards of acceptable behavior and will take appropriate and fair corrective action in response to any behavior that they deem inappropriate, threatening, offensive, or harmful.
33
+
34
+ Community leaders have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct, and will communicate reasons for moderation decisions when appropriate.
35
+
36
+ ## Scope
37
+
38
+ This Code of Conduct applies within all community spaces, and also applies when an individual is officially representing the community in public spaces. Examples of representing our community include using an official e-mail address, posting via an official social media account, or acting as an appointed representative at an online or offline event.
39
+
40
+ ## Enforcement
41
+
42
+ Instances of abusive, harassing, or otherwise unacceptable behavior may be reported to the community leaders responsible for enforcement at howeszy@gmail.com. All complaints will be reviewed and investigated promptly and fairly.
43
+
44
+ All community leaders are obligated to respect the privacy and security of the reporter of any incident.
45
+
46
+ ## Enforcement Guidelines
47
+
48
+ Community leaders will follow these Community Impact Guidelines in determining the consequences for any action they deem in violation of this Code of Conduct:
49
+
50
+ ### 1. Correction
51
+
52
+ **Community Impact**: Use of inappropriate language or other behavior deemed unprofessional or unwelcome in the community.
53
+
54
+ **Consequence**: A private, written warning from community leaders, providing clarity around the nature of the violation and an explanation of why the behavior was inappropriate. A public apology may be requested.
55
+
56
+ ### 2. Warning
57
+
58
+ **Community Impact**: A violation through a single incident or series of actions.
59
+
60
+ **Consequence**: A warning with consequences for continued behavior. No interaction with the people involved, including unsolicited interaction with those enforcing the Code of Conduct, for a specified period of time. This includes avoiding interactions in community spaces as well as external channels like social media. Violating these terms may lead to a temporary or permanent ban.
61
+
62
+ ### 3. Temporary Ban
63
+
64
+ **Community Impact**: A serious violation of community standards, including sustained inappropriate behavior.
65
+
66
+ **Consequence**: A temporary ban from any sort of interaction or public communication with the community for a specified period of time. No public or private interaction with the people involved, including unsolicited interaction with those enforcing the Code of Conduct, is allowed during this period. Violating these terms may lead to a permanent ban.
67
+
68
+ ### 4. Permanent Ban
69
+
70
+ **Community Impact**: Demonstrating a pattern of violation of community standards, including sustained inappropriate behavior, harassment of an individual, or aggression toward or disparagement of classes of individuals.
71
+
72
+ **Consequence**: A permanent ban from any sort of public interaction within the community.
73
+
74
+ ## Attribution
75
+
76
+ This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 2.0,
77
+ available at https://www.contributor-covenant.org/version/2/0/code_of_conduct.html.
78
+
79
+ Community Impact Guidelines were inspired by [Mozilla's code of conduct enforcement ladder](https://github.com/mozilla/diversity).
80
+
81
+ [homepage]: https://www.contributor-covenant.org
82
+
83
+ For answers to common questions about this code of conduct, see the FAQ at
84
+ https://www.contributor-covenant.org/faq. Translations are available at https://www.contributor-covenant.org/translations.
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 snfoil-policy.gemspec
6
+ gemspec
data/LICENSE.txt ADDED
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ https://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "{}"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright {yyyy} {name of copyright owner}
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ https://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
data/README.md ADDED
@@ -0,0 +1,274 @@
1
+ # SnFoil::Context
2
+
3
+ ![build](https://github.com/limited-effort/snfoil-context/actions/workflows/main.yml/badge.svg) [![maintainability](https://api.codeclimate.com/v1/badges/6a7a2f643707c17cb879/maintainability)](https://codeclimate.com/github/limited-effort/snfoil-context/maintainability)
4
+
5
+ SnFoil Contexts are a simple way to insure a workflow pipeline can be easily established end extended. It helps by creating workflow, allowing additional in steps at specific intervals, and reacting to a success or failure, you should find your code being more maintainable and testable.
6
+
7
+ ## Installation
8
+
9
+ Add this line to your application's Gemfile:
10
+
11
+ ```ruby
12
+ gem 'snfoil-context'
13
+ ```
14
+
15
+ ## Usage
16
+ While contexts are powerful, they aren't a magic bullet. Each function should strive to only contain a single purpose. This also has the added benefit of outlining some basic tests - if it is in a function it should have a related test.
17
+
18
+ ### Action
19
+ To start you will need to define an action.
20
+
21
+ Arguments:
22
+ * `name` - The name of this action will also set the name of all the hooks and methods later generated.
23
+ * `with` - Keyword Param - The method name of the primary action. Either this or a block is required
24
+ * `block` - Block - The block of the primary action. Either this or with is required
25
+
26
+ ```ruby
27
+ # lib/contexts/token_context
28
+ require 'snfoil/context'
29
+
30
+ class TokenContext
31
+ include SnFoil::Context
32
+
33
+ action :expire { |options| options[:object].update(expired_at: Time.current) }
34
+ end
35
+ ```
36
+
37
+ This will generate the methods and hooks of the pipeline. In this example the following get made:
38
+ * setup_expire
39
+ * before_expire
40
+ * after_expire_success
41
+ * after_expire_failure
42
+ * after_expire
43
+
44
+ If you want to reuse the primary action or just prefer methods, you can pass in the method name you would like to call, rather than providing a block. If a method name and a block is provided, the block is ignored.
45
+
46
+
47
+ ```ruby
48
+ # lib/contexts/token_context
49
+ require 'snfoil/context'
50
+
51
+ class TokenContext
52
+ include SnFoil::Context
53
+
54
+ action :expire, with: :expire_token
55
+
56
+ def expire_token(options)
57
+ options[:object].update(expired_at: Time.current)
58
+ end
59
+ end
60
+ ```
61
+
62
+ #### Primary Actions
63
+ The primary action is the function that determine whether or not the action is successful. To do this, the primary action must always return a truthy value if the action was successful, or a falsey one if it failed.
64
+
65
+ The primary action is passed one argument which is the return value of the closest preceeding interval function.
66
+
67
+ ```ruby
68
+ # lib/contexts/token_context
69
+ require 'snfoil/context'
70
+
71
+ class TokenContext
72
+ include SnFoil::Context
73
+
74
+ action :expire, with: :expire_token
75
+
76
+ before_expire do |options|
77
+ options[:foo] = bar
78
+ options
79
+ end
80
+
81
+ def expire_token(options)
82
+ puts options[:foo] # => logs 'bar' to the console
83
+ ...
84
+ end
85
+ end
86
+ ```
87
+
88
+ #### Intervals
89
+ The following are the intervals SnFoil Contexts sets up in the order they occur. The suggested uses are just very simply examples. You can chain contexts to setup very complex interactions in a very easy to manage workflow.
90
+
91
+ <table>
92
+ <thead>
93
+ <th>Name</th>
94
+ <th>Suggested Use</th>
95
+ </thead>
96
+ <tbody>
97
+ <tr>
98
+ <td>setup_&lt;action&gt;</td>
99
+ <td>
100
+ <div>* find or create a model</div>
101
+ <div>* setup params needed later in the action</div>
102
+ <div>* set scoping </div>
103
+ </td>
104
+ </tr>
105
+ <tr>
106
+ <td>before_&lt;action&gt;</td>
107
+ <td>
108
+ <div>* alter model or set attributes</div>
109
+ </td>
110
+ </tr>
111
+ <tr>
112
+ <td>primary action</td>
113
+ <td>
114
+ <div>* persist database changes</div>
115
+ <div>* make primary network call</div>
116
+ </td>
117
+ </tr>
118
+ <tr>
119
+ <td>after_&lt;action&gt;_success</td>
120
+ <td>
121
+ <div>* setup additional relationships</div>
122
+ <div>* success specific logging</div>
123
+ </td>
124
+ </tr>
125
+ <tr>
126
+ <td>after_&lt;action&gt;_failure</td>
127
+ <td>
128
+ <div>* cleanup failed remenants</div>
129
+ <div>* call bug tracker</div>
130
+ <div>* failure specific logging</div>
131
+ </td>
132
+ </tr>
133
+ <tr>
134
+ <td>after_&lt;action&gt;</td>
135
+ <td>
136
+ <div>* perform necessary required cleanup</div>
137
+ <div>* log outcome</div>
138
+ </td>
139
+ </tr>
140
+ </tbody>
141
+ <table>
142
+
143
+
144
+ #### Hook and Method Design
145
+
146
+ SnFoil Contexts try hard to not store variables longer than necessary. To facilitate this we have choosen to pass an object (we normally use a hash called options) to each hook and method, and the return from the hook or method is passed down the chain to the next hook or method.
147
+
148
+ The only method or block that does not get its value passwed down the chain is the primary action - which must always return a truthy value of whether or not the action was successful.
149
+
150
+ #### Hooks
151
+ Hooks make it very easy to compose multiple actions that need to occur in a specific order. You can have as many repeated hooks as you would like. This makes defining single responsibility hooks very simple, and they will get called in the order they are defined.
152
+
153
+ <strong>Important Note</strong> Hooks <u>always</u> need to return the options hash at the end.
154
+
155
+ ##### Example
156
+ ```ruby
157
+ # Call the webhooks for third party integrations
158
+ after_expire_success do |options|
159
+ call_webhook_for_model(options[:object])
160
+ options
161
+ end
162
+
163
+ # Commit business logic to internal process
164
+ after_expire_success do |options|
165
+ finalize_business_logic(options[:object])
166
+ options
167
+ end
168
+
169
+ # notify error tracker
170
+ after_expire_error do |options|
171
+ notify_errors(options[:object].errors)
172
+ options
173
+ end
174
+ ```
175
+
176
+ #### Methods
177
+ Methods allow users to create inheritable actions that occur in a specific order. Methods will always run after their hook counterpart. Since these are inheritable, you can chain needed actions all the way through the parent heirarchy by using the `super` keyword.
178
+
179
+ <strong>Important Note</strong> Methods <u>always</u> need to return the options hash at the end.
180
+
181
+ <i>Author's opinion:</i> While simplier than hooks, they do not allow for as clean of a composition as hooks.
182
+
183
+ ##### Example
184
+
185
+ ```ruby
186
+ # Call the webhooks for third party integrations
187
+ # Commit business logic to internal process
188
+ def after_expire_success(**options)
189
+ options = super
190
+
191
+ call_webhook_for_model(options[:object])
192
+ finalize_business_logic(options[:object])
193
+
194
+ options
195
+ end
196
+
197
+ # notify error tracker
198
+ def after_expire_error(**options)
199
+ options = super
200
+
201
+ notify_errors(options[:object].errors)
202
+
203
+ options
204
+ end
205
+ ```
206
+
207
+ ### Authorize
208
+ The original purpose of all of SnFoil was to ensure there was a good consistent way to authenticate and authorize entities. As such authorize hooks were built directly into the workflow.
209
+
210
+ These authorization hooks are always called twice. Once after `setup_<action>` and once after `before_<action>`
211
+
212
+ The `authorize` method functions much like primary action except the first argument is usually the name of action you are authorizing.
213
+
214
+ Arguments:
215
+ * `name` - The name of this action to be authorized. If ommited, all actions without a specific associated authorize will use this one..
216
+ * `with` - Keyword Param - The method name of the primary action. Either this or a block is required
217
+ * `block` - Block - The block of the primary action. Either this or with is required
218
+
219
+ ```ruby
220
+ # lib/contexts/token_context
221
+ require 'snfoil/context'
222
+
223
+ class TokenContext
224
+ include SnFoil::Context
225
+
226
+ action :expire, with: :expire_token
227
+
228
+ authorize :expire { |options| options[:entity].is_admin? }
229
+
230
+ ...
231
+ end
232
+ ```
233
+
234
+ You can also call authorize without an action name. This will have all action authorize with the provided method or block unless there is a more specific authorize action configured. Its probably easier explained with an example
235
+
236
+
237
+ ```ruby
238
+ # lib/contexts/token_context
239
+ require 'snfoil/context'
240
+
241
+ class TokenContext
242
+ include SnFoil::Context
243
+
244
+ action :expire, with: :expire_token #=> will authorize by checking the entity is an admin
245
+ action :search, with: :query_tokens #=> will authorize by checking the entity is a user
246
+ action :show, with: :find_token #=> will authorize by checking the entity is a user
247
+
248
+ authorize :expire { |options| options[:entity].is_admin? }
249
+ authorize { |options| options[:entity].is_user? }
250
+
251
+ ...
252
+ end
253
+ ```
254
+
255
+ #### Why before and after?
256
+ Simply to make sure the entity it actually allowed access the primary target and is allowed to make the requested alterations/interactions.
257
+
258
+ ## Development
259
+
260
+ 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.
261
+
262
+ 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 the created tag, and push the `.gem` file to [rubygems.org](https://rubygems.org).
263
+
264
+ ## Contributing
265
+
266
+ Bug reports and pull requests are welcome on GitHub at https://github.com/limited-effort/snfoil-context. 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/limited-effort/snfoil-context/blob/main/CODE_OF_CONDUCT.md).
267
+
268
+ ## License
269
+
270
+ The gem is available as open source under the terms of the [Apache 2 License](https://opensource.org/licenses/Apache-2.0).
271
+
272
+ ## Code of Conduct
273
+
274
+ Everyone interacting in the Snfoil::Context project's codebases, issue trackers, chat rooms and mailing lists is expected to follow the [code of conduct](https://github.com/limited-effort/snfoil-context/blob/main/CODE_OF_CONDUCT.md).
data/Rakefile ADDED
@@ -0,0 +1,12 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'bundler/gem_tasks'
4
+ require 'rspec/core/rake_task'
5
+
6
+ RSpec::Core::RakeTask.new(:spec)
7
+
8
+ require 'rubocop/rake_task'
9
+
10
+ RuboCop::RakeTask.new
11
+
12
+ task default: %i[spec rubocop]
data/bin/console ADDED
@@ -0,0 +1,15 @@
1
+ #!/usr/bin/env ruby
2
+ # frozen_string_literal: true
3
+
4
+ require 'bundler/setup'
5
+ require 'snfoil/policy'
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__)
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,21 @@
1
+ # frozen_string_literal: true
2
+
3
+ # Copyright 2021 Matthew Howes
4
+
5
+ # Licensed under the Apache License, Version 2.0 (the "License");
6
+ # you may not use this file except in compliance with the License.
7
+ # You may obtain a copy of the License at
8
+
9
+ # http://www.apache.org/licenses/LICENSE-2.0
10
+
11
+ # Unless required by applicable law or agreed to in writing, software
12
+ # distributed under the License is distributed on an "AS IS" BASIS,
13
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ # See the License for the specific language governing permissions and
15
+ # limitations under the License.
16
+
17
+ module SnFoil
18
+ module Context
19
+ class ArgumentError < ::ArgumentError; end
20
+ end
21
+ end
@@ -0,0 +1,21 @@
1
+ # frozen_string_literal: true
2
+
3
+ # Copyright 2021 Matthew Howes
4
+
5
+ # Licensed under the Apache License, Version 2.0 (the "License");
6
+ # you may not use this file except in compliance with the License.
7
+ # You may obtain a copy of the License at
8
+
9
+ # http://www.apache.org/licenses/LICENSE-2.0
10
+
11
+ # Unless required by applicable law or agreed to in writing, software
12
+ # distributed under the License is distributed on an "AS IS" BASIS,
13
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ # See the License for the specific language governing permissions and
15
+ # limitations under the License.
16
+
17
+ module SnFoil
18
+ module Context
19
+ class Error < RuntimeError; end
20
+ end
21
+ end
@@ -0,0 +1,79 @@
1
+ # frozen_string_literal: true
2
+
3
+ # Copyright 2021 Matthew Howes
4
+
5
+ # Licensed under the Apache License, Version 2.0 (the "License");
6
+ # you may not use this file except in compliance with the License.
7
+ # You may obtain a copy of the License at
8
+
9
+ # http://www.apache.org/licenses/LICENSE-2.0
10
+
11
+ # Unless required by applicable law or agreed to in writing, software
12
+ # distributed under the License is distributed on an "AS IS" BASIS,
13
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ # See the License for the specific language governing permissions and
15
+ # limitations under the License.
16
+
17
+ require_relative './error'
18
+ require 'active_support/concern'
19
+
20
+ module SnFoil
21
+ module Context
22
+ # Basic structure needed to support a SnFoil context
23
+ #
24
+ # @author Matthew Howes
25
+ #
26
+ # @since 0.1.0
27
+ module Structure
28
+ extend ActiveSupport::Concern
29
+
30
+ class_methods do
31
+ attr_reader :i_authorizations
32
+
33
+ def authorize(action_name = nil, with: nil, &block)
34
+ @i_authorizations ||= {}
35
+ action_name = action_name&.to_sym
36
+
37
+ raise SnFoil::Context::Error, "#{name} already has authorize defined for #{action_name || ':default'}" if @i_authorizations[action_name]
38
+
39
+ @i_authorizations[action_name] = { method: with, block: block }
40
+ end
41
+ end
42
+
43
+ attr_reader :entity
44
+
45
+ def initialize(entity = nil)
46
+ @entity = entity
47
+ end
48
+
49
+ def authorize(name, **options)
50
+ configured_call = self.class.i_authorizations&.fetch(name.to_sym, nil)
51
+ configured_call ||= self.class.i_authorizations&.fetch(nil, nil)
52
+
53
+ if configured_call
54
+ run_hook(configured_call, **options)
55
+ else
56
+ SnFoil.logger.info "No configuration for #{name} in #{self.class.name}. Authorize not called" if SnFoil.respond_to?(:logger)
57
+ true
58
+ end
59
+ end
60
+
61
+ private
62
+
63
+ def run_hook(hook, **options)
64
+ return options unless hook && hook_valid?(hook, **options)
65
+
66
+ return send(hook[:method], **options) if hook[:method]
67
+
68
+ instance_exec options, &hook[:block]
69
+ end
70
+
71
+ def hook_valid?(hook, **options)
72
+ return false if !hook[:if].nil? && hook[:if].call(options) == false
73
+ return false if !hook[:unless].nil? && hook[:unless].call(options) == true
74
+
75
+ true
76
+ end
77
+ end
78
+ end
79
+ end
@@ -0,0 +1,21 @@
1
+ # frozen_string_literal: true
2
+
3
+ # Copyright 2021 Matthew Howes
4
+
5
+ # Licensed under the Apache License, Version 2.0 (the "License");
6
+ # you may not use this file except in compliance with the License.
7
+ # You may obtain a copy of the License at
8
+
9
+ # http://www.apache.org/licenses/LICENSE-2.0
10
+
11
+ # Unless required by applicable law or agreed to in writing, software
12
+ # distributed under the License is distributed on an "AS IS" BASIS,
13
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ # See the License for the specific language governing permissions and
15
+ # limitations under the License.
16
+
17
+ module SnFoil
18
+ module Context
19
+ VERSION = '0.0.1'
20
+ end
21
+ end
@@ -0,0 +1,110 @@
1
+ # frozen_string_literal: true
2
+
3
+ # Copyright 2021 Matthew Howes
4
+
5
+ # Licensed under the Apache License, Version 2.0 (the "License");
6
+ # you may not use this file except in compliance with the License.
7
+ # You may obtain a copy of the License at
8
+
9
+ # http://www.apache.org/licenses/LICENSE-2.0
10
+
11
+ # Unless required by applicable law or agreed to in writing, software
12
+ # distributed under the License is distributed on an "AS IS" BASIS,
13
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ # See the License for the specific language governing permissions and
15
+ # limitations under the License.
16
+
17
+ require_relative './context/error'
18
+ require_relative './context/argument_error'
19
+ require_relative './context/structure'
20
+
21
+ require 'active_support/concern'
22
+
23
+ module SnFoil
24
+ # ActiveSupport::Concern for adding SnFoil Context functionality
25
+ #
26
+ # @author Matthew Howes
27
+ #
28
+ # @since 0.1.0
29
+ module Context
30
+ extend ActiveSupport::Concern
31
+
32
+ included do
33
+ include SnFoil::Context::Structure
34
+ end
35
+
36
+ class_methods do
37
+ def action(name, with: nil, &block)
38
+ raise SnFoil::Context::Error, "action #{name} already defined for #{self.name}" if (@defined_actions ||= []).include?(name)
39
+
40
+ @defined_actions << name
41
+ setup_hooks(name)
42
+ define_action_primary(name, with, block)
43
+ end
44
+ end
45
+
46
+ private
47
+
48
+ # rubocop:disable reason: These are builder/mapping methods that are just too complex to simplify without
49
+ # making them more complex. If anyone has a better way please let me know
50
+ class_methods do # rubocop:disable Metrics/BlockLength
51
+ def define_action_primary(name, method, block) # rubocop:disable Metrics/AbcSize, Metrics/MethodLength
52
+ define_method(name) do |**options| # rubocop:disable Metrics/MethodLength
53
+ options[:action] = name.to_sym
54
+ options = run_action_group(format('setup_%s', name), **options)
55
+ authorize(name, **options) if respond_to?(:authorize)
56
+
57
+ options = run_action_group(format('before_%s', name), **options)
58
+ authorize(name, **options) if respond_to?(:authorize)
59
+
60
+ options = if run_action_primary(method, block, **options)
61
+ run_action_group(format('after_%s_success', name), **options)
62
+ else
63
+ run_action_group(format('after_%s_failure', name), **options)
64
+ end
65
+ run_action_group(format('after_%s', name), **options)
66
+ end
67
+ end
68
+
69
+ def setup_hooks(name)
70
+ hook_builder('setup_%s', name)
71
+ hook_builder('before_%s', name)
72
+ hook_builder('after_%s_success', name)
73
+ hook_builder('after_%s_failure', name)
74
+ hook_builder('after_%s', name)
75
+ end
76
+
77
+ def hook_builder(name_format, name)
78
+ assign_singleton_methods format(name_format, name),
79
+ format("#{name_format}_hooks", name)
80
+ end
81
+
82
+ def assign_singleton_methods(method_name, singleton_var)
83
+ instance_variable_set("@#{singleton_var}", [])
84
+ define_singleton_method(singleton_var) { instance_variable_get("@#{singleton_var}") }
85
+ define_singleton_method(method_name) do |method = nil, **options, &block|
86
+ raise SnFoil::Context::ArgumentError, "\##{method_name} requires either a method name or a block" if method.nil? && block.nil?
87
+
88
+ instance_variable_get("@#{singleton_var}") << { method: method,
89
+ block: block,
90
+ if: options[:if],
91
+ unless: options[:unless] }
92
+ end
93
+ end
94
+ end
95
+
96
+ def run_action_primary(method, block, **options)
97
+ return send(method, **options) if method
98
+
99
+ instance_exec options, &block
100
+ end
101
+
102
+ def run_action_group(group_name, **options)
103
+ options = self.class.instance_variable_get("@#{group_name}_hooks")
104
+ .reduce(options) { |opts, hook| run_hook(hook, opts) }
105
+ options = send(group_name, **options) if respond_to?(group_name)
106
+
107
+ options
108
+ end
109
+ end
110
+ end
@@ -0,0 +1,39 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative 'lib/snfoil/context/version'
4
+
5
+ Gem::Specification.new do |spec|
6
+ spec.name = 'snfoil-context'
7
+ spec.version = SnFoil::Context::VERSION
8
+ spec.authors = ['Matthew Howes']
9
+ spec.email = ['howeszy@gmail.com']
10
+
11
+ spec.summary = ''
12
+ spec.description = ''
13
+ spec.homepage = 'https://github.com/limited-effort/snfoil-context'
14
+ spec.license = 'MIT'
15
+ spec.required_ruby_version = '>= 2.5.0'
16
+
17
+ spec.metadata['homepage_uri'] = spec.homepage
18
+ spec.metadata['source_code_uri'] = spec.homepage
19
+ spec.metadata['changelog_uri'] = 'https://github.com/limited-effort/snfoil-context/blob/main/CHANGELOG.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(__dir__)) do
24
+ `git ls-files -z`.split("\x0").reject { |f| f.match(%r{\A(?:test|spec|features)/}) }
25
+ end
26
+
27
+ spec.bindir = 'exe'
28
+ spec.executables = spec.files.grep(%r{\Aexe/}) { |f| File.basename(f) }
29
+ spec.require_paths = ['lib']
30
+
31
+ spec.add_dependency 'activesupport', '>= 5.2.6'
32
+
33
+ spec.add_development_dependency 'pry-byebug', '~> 3.9'
34
+ spec.add_development_dependency 'rake', '~> 13.0'
35
+ spec.add_development_dependency 'rspec', '~> 3.10'
36
+ spec.add_development_dependency 'rubocop', '~> 1.21'
37
+ spec.add_development_dependency 'rubocop-performance', '~> 1.11'
38
+ spec.add_development_dependency 'rubocop-rspec', '~> 2.5'
39
+ end
metadata ADDED
@@ -0,0 +1,162 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: snfoil-context
3
+ version: !ruby/object:Gem::Version
4
+ version: 0.0.1
5
+ platform: ruby
6
+ authors:
7
+ - Matthew Howes
8
+ autorequire:
9
+ bindir: exe
10
+ cert_chain: []
11
+ date: 2021-10-12 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.2.6
20
+ type: :runtime
21
+ prerelease: false
22
+ version_requirements: !ruby/object:Gem::Requirement
23
+ requirements:
24
+ - - ">="
25
+ - !ruby/object:Gem::Version
26
+ version: 5.2.6
27
+ - !ruby/object:Gem::Dependency
28
+ name: pry-byebug
29
+ requirement: !ruby/object:Gem::Requirement
30
+ requirements:
31
+ - - "~>"
32
+ - !ruby/object:Gem::Version
33
+ version: '3.9'
34
+ type: :development
35
+ prerelease: false
36
+ version_requirements: !ruby/object:Gem::Requirement
37
+ requirements:
38
+ - - "~>"
39
+ - !ruby/object:Gem::Version
40
+ version: '3.9'
41
+ - !ruby/object:Gem::Dependency
42
+ name: rake
43
+ requirement: !ruby/object:Gem::Requirement
44
+ requirements:
45
+ - - "~>"
46
+ - !ruby/object:Gem::Version
47
+ version: '13.0'
48
+ type: :development
49
+ prerelease: false
50
+ version_requirements: !ruby/object:Gem::Requirement
51
+ requirements:
52
+ - - "~>"
53
+ - !ruby/object:Gem::Version
54
+ version: '13.0'
55
+ - !ruby/object:Gem::Dependency
56
+ name: rspec
57
+ requirement: !ruby/object:Gem::Requirement
58
+ requirements:
59
+ - - "~>"
60
+ - !ruby/object:Gem::Version
61
+ version: '3.10'
62
+ type: :development
63
+ prerelease: false
64
+ version_requirements: !ruby/object:Gem::Requirement
65
+ requirements:
66
+ - - "~>"
67
+ - !ruby/object:Gem::Version
68
+ version: '3.10'
69
+ - !ruby/object:Gem::Dependency
70
+ name: rubocop
71
+ requirement: !ruby/object:Gem::Requirement
72
+ requirements:
73
+ - - "~>"
74
+ - !ruby/object:Gem::Version
75
+ version: '1.21'
76
+ type: :development
77
+ prerelease: false
78
+ version_requirements: !ruby/object:Gem::Requirement
79
+ requirements:
80
+ - - "~>"
81
+ - !ruby/object:Gem::Version
82
+ version: '1.21'
83
+ - !ruby/object:Gem::Dependency
84
+ name: rubocop-performance
85
+ requirement: !ruby/object:Gem::Requirement
86
+ requirements:
87
+ - - "~>"
88
+ - !ruby/object:Gem::Version
89
+ version: '1.11'
90
+ type: :development
91
+ prerelease: false
92
+ version_requirements: !ruby/object:Gem::Requirement
93
+ requirements:
94
+ - - "~>"
95
+ - !ruby/object:Gem::Version
96
+ version: '1.11'
97
+ - !ruby/object:Gem::Dependency
98
+ name: rubocop-rspec
99
+ requirement: !ruby/object:Gem::Requirement
100
+ requirements:
101
+ - - "~>"
102
+ - !ruby/object:Gem::Version
103
+ version: '2.5'
104
+ type: :development
105
+ prerelease: false
106
+ version_requirements: !ruby/object:Gem::Requirement
107
+ requirements:
108
+ - - "~>"
109
+ - !ruby/object:Gem::Version
110
+ version: '2.5'
111
+ description: ''
112
+ email:
113
+ - howeszy@gmail.com
114
+ executables: []
115
+ extensions: []
116
+ extra_rdoc_files: []
117
+ files:
118
+ - ".github/workflows/main.yml"
119
+ - ".gitignore"
120
+ - ".rspec"
121
+ - ".rubocop.yml"
122
+ - CHANGELOG.md
123
+ - CODE_OF_CONDUCT.md
124
+ - Gemfile
125
+ - LICENSE.txt
126
+ - README.md
127
+ - Rakefile
128
+ - bin/console
129
+ - bin/setup
130
+ - lib/snfoil/context.rb
131
+ - lib/snfoil/context/argument_error.rb
132
+ - lib/snfoil/context/error.rb
133
+ - lib/snfoil/context/structure.rb
134
+ - lib/snfoil/context/version.rb
135
+ - snfoil-policy.gemspec
136
+ homepage: https://github.com/limited-effort/snfoil-context
137
+ licenses:
138
+ - MIT
139
+ metadata:
140
+ homepage_uri: https://github.com/limited-effort/snfoil-context
141
+ source_code_uri: https://github.com/limited-effort/snfoil-context
142
+ changelog_uri: https://github.com/limited-effort/snfoil-context/blob/main/CHANGELOG.md
143
+ post_install_message:
144
+ rdoc_options: []
145
+ require_paths:
146
+ - lib
147
+ required_ruby_version: !ruby/object:Gem::Requirement
148
+ requirements:
149
+ - - ">="
150
+ - !ruby/object:Gem::Version
151
+ version: 2.5.0
152
+ required_rubygems_version: !ruby/object:Gem::Requirement
153
+ requirements:
154
+ - - ">="
155
+ - !ruby/object:Gem::Version
156
+ version: '0'
157
+ requirements: []
158
+ rubygems_version: 3.1.6
159
+ signing_key:
160
+ specification_version: 4
161
+ summary: ''
162
+ test_files: []