hooksmith 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.
checksums.yaml ADDED
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA256:
3
+ metadata.gz: ef153cc049df6fb2994b69e8e7fc5a260c1cb57262a7157871b36baf38aff34d
4
+ data.tar.gz: a0fb98c2d45e68e4adca1bbd0fc9a3ed44747cff6aa8f56b78ef1bcc6222d4d3
5
+ SHA512:
6
+ metadata.gz: 7bfdc41f3a150ebb6c9ee9685ee22f3d8d3eabbd0314dbb0a42b855f41ead9a3277d0fe8049aef6b05034c6efa540cd17a5d017906b5432000af3f8532a7513b
7
+ data.tar.gz: bcd1dd3624624bdfcc288591b1cfde025c3ccfce80f71fcbc649ee8119b2f143bf00c5edc899c7db3b4acf0572d0ebbd802909663a3231c215c645971ceb4b95
data/.DS_Store ADDED
Binary file
data/.rubocop.yml ADDED
@@ -0,0 +1,419 @@
1
+ AllCops:
2
+ NewCops: enable
3
+
4
+ # Style
5
+ Style/StringLiterals:
6
+ EnforcedStyle: single_quotes
7
+ Style/FrozenStringLiteralComment:
8
+ Enabled: true
9
+ EnforcedStyle: always
10
+ Style/Documentation:
11
+ Enabled: true
12
+ Exclude:
13
+ - 'db/schema.rb'
14
+ - 'db/migrate/*'
15
+ Style/AsciiComments:
16
+ Enabled: false
17
+ Style/BisectedAttrAccessor:
18
+ Enabled: true
19
+ Style/CaseLikeIf:
20
+ Enabled: true
21
+ Style/ClassEqualityComparison:
22
+ Enabled: true
23
+ Style/CollectionCompact:
24
+ Enabled: true
25
+ Style/CombinableLoops:
26
+ Enabled: true
27
+ Style/ConcatArrayLiterals:
28
+ Enabled: true
29
+ Style/ConditionalAssignment:
30
+ EnforcedStyle: assign_to_condition
31
+ Style/DirEmpty:
32
+ Enabled: true
33
+ Style/DocumentDynamicEvalDefinition:
34
+ Enabled: true
35
+ Style/EmptyMethod:
36
+ EnforcedStyle: compact
37
+ Style/EmptyHeredoc:
38
+ Enabled: true
39
+ Style/EndlessMethod:
40
+ Enabled: true
41
+ EnforcedStyle: disallow
42
+ Style/EnvHome:
43
+ Enabled: true
44
+ Style/ExactRegexpMatch:
45
+ Enabled: true
46
+ Style/FetchEnvVar:
47
+ Enabled: true
48
+ Style/FileEmpty:
49
+ Enabled: true
50
+ Style/FileRead:
51
+ Enabled: true
52
+ Style/FileWrite:
53
+ Enabled: true
54
+ Style/HashAsLastArrayItem:
55
+ Enabled: true
56
+ Style/HashConversion:
57
+ Enabled: true
58
+ Style/HashEachMethods:
59
+ Enabled: true
60
+ Style/HashExcept:
61
+ Enabled: true
62
+ Style/HashLikeCase:
63
+ Enabled: true
64
+ Style/HashSyntax:
65
+ EnforcedShorthandSyntax: always
66
+ Style/HashTransformKeys:
67
+ Enabled: true
68
+ Style/HashTransformValues:
69
+ Enabled: true
70
+ Style/IfWithBooleanLiteralBranches:
71
+ Enabled: true
72
+ Style/InPatternThen:
73
+ Enabled: true
74
+ Style/KeywordParametersOrder:
75
+ Enabled: true
76
+ Style/MagicCommentFormat:
77
+ Enabled: true
78
+ Style/MapCompactWithConditionalBlock:
79
+ Enabled: true
80
+ Style/MapToHash:
81
+ Enabled: true
82
+ Style/MapToSet:
83
+ Enabled: true
84
+ Style/MinMaxComparison:
85
+ Enabled: true
86
+ Style/NegatedIfElseCondition:
87
+ Enabled: true
88
+ Style/NumberedParameters:
89
+ Enabled: true
90
+ EnforcedStyle: disallow
91
+ Style/OperatorMethodCall:
92
+ Enabled: true
93
+ Style/QuotedSymbols:
94
+ Enabled: true
95
+ Style/RedundantArgument:
96
+ Enabled: true
97
+ Style/RedundantAssignment:
98
+ Enabled: true
99
+ Style/RedundantDoubleSplatHashBraces:
100
+ Enabled: true
101
+ Style/RedundantEach:
102
+ Enabled: true
103
+ Style/RedundantFetchBlock:
104
+ Enabled: true
105
+ Style/RedundantInitialize:
106
+ Enabled: true
107
+ Style/RedundantSelfAssignment:
108
+ Enabled: false
109
+ Style/RedundantSelfAssignmentBranch:
110
+ Enabled: true
111
+ Style/RedundantStringEscape:
112
+ Enabled: true
113
+ Style/ReturnNilInPredicateMethodDefinition:
114
+ Enabled: true
115
+ Style/SoleNestedConditional:
116
+ Enabled: true
117
+ Style/StringChars:
118
+ Enabled: true
119
+ Style/StringConcatenation:
120
+ Enabled: true
121
+ Style/SwapValues:
122
+ Enabled: true
123
+ Style/YAMLFileRead:
124
+ Enabled: true
125
+ Style/AmbiguousEndlessMethodDefinition:
126
+ Enabled: true
127
+ Style/ArgumentsForwarding:
128
+ Enabled: true
129
+ Style/ArrayIntersect:
130
+ Enabled: true
131
+ Style/BitwisePredicate:
132
+ Enabled: true
133
+ Style/CombinableDefined:
134
+ Enabled: true
135
+ Style/ComparableClamp:
136
+ Enabled: true
137
+ Style/DataInheritance:
138
+ Enabled: true
139
+ Style/DigChain:
140
+ Enabled: true
141
+ Style/FileNull:
142
+ Enabled: true
143
+ Style/FileTouch:
144
+ Enabled: true
145
+ Style/HashSlice:
146
+ Enabled: true
147
+ Style/ItAssignment:
148
+ Enabled: true
149
+ Style/KeywordArgumentsMerging:
150
+ Enabled: true
151
+ Style/MapIntoArray:
152
+ Enabled: true
153
+ Style/MultilineInPatternThen:
154
+ Enabled: true
155
+ Style/NestedFileDirname:
156
+ Enabled: true
157
+ Style/NilLambda:
158
+ Enabled: true
159
+ Style/NumberedParametersLimit:
160
+ Enabled: true
161
+ Style/ObjectThen:
162
+ Enabled: true
163
+ Style/OpenStructUse:
164
+ Enabled: true
165
+ Style/RedundantArrayConstructor:
166
+ Enabled: true
167
+ Style/RedundantConstantBase:
168
+ Enabled: true
169
+ Style/RedundantCurrentDirectoryInPath:
170
+ Enabled: true
171
+ Style/RedundantFilterChain:
172
+ Enabled: true
173
+ Style/RedundantFormat:
174
+ Enabled: true
175
+ Style/RedundantHeredocDelimiterQuotes:
176
+ Enabled: true
177
+ Style/RedundantInterpolationUnfreeze:
178
+ Enabled: true
179
+ Style/RedundantLineContinuation:
180
+ Enabled: true
181
+ Style/RedundantRegexpArgument:
182
+ Enabled: true
183
+ Style/RedundantRegexpConstructor:
184
+ Enabled: true
185
+ Style/SafeNavigationChainLength:
186
+ Enabled: true
187
+ Style/SelectByRegexp:
188
+ Enabled: true
189
+ Style/SendWithLiteralMethodName:
190
+ Enabled: true
191
+ Style/SingleLineDoEndBlock:
192
+ Enabled: true
193
+ Style/SuperArguments:
194
+ Enabled: true
195
+ Style/SuperWithArgsParentheses:
196
+ Enabled: true
197
+
198
+ # Metrics
199
+ Metrics/MethodLength:
200
+ Max: 20
201
+
202
+ Metrics/AbcSize:
203
+ Enabled: false
204
+ Metrics/ClassLength:
205
+ Enabled: false
206
+ Metrics/CollectionLiteralLength:
207
+ Enabled: true
208
+
209
+ # Layout
210
+ Layout/SpaceInsideArrayLiteralBrackets:
211
+ EnforcedStyle: no_space
212
+ Layout/EmptyLineAfterGuardClause:
213
+ Enabled: true
214
+ Layout/LineLength:
215
+ Max: 120
216
+ Exclude:
217
+ - 'Gemfile'
218
+ Layout/BeginEndAlignment:
219
+ Enabled: true
220
+ EnforcedStyleAlignWith: start_of_line
221
+ Layout/CommentIndentation:
222
+ Enabled: true
223
+ Layout/DotPosition:
224
+ EnforcedStyle: leading
225
+ Layout/EmptyLinesAroundAttributeAccessor:
226
+ Enabled: true
227
+ Layout/LineContinuationSpacing:
228
+ Enabled: true
229
+ Layout/LineEndStringConcatenationIndentation:
230
+ Enabled: true
231
+ EnforcedStyle: indented
232
+ Layout/SpaceAroundMethodCallOperator:
233
+ Enabled: true
234
+ Layout/SpaceBeforeBrackets:
235
+ Enabled: true
236
+ Layout/LineContinuationLeadingSpace:
237
+ Enabled: true
238
+
239
+ # Lint
240
+ Lint/AmbiguousAssignment:
241
+ Enabled: true
242
+ Lint/AmbiguousOperatorPrecedence:
243
+ Enabled: true
244
+ Lint/AmbiguousRange:
245
+ Enabled: true
246
+ Lint/ArrayLiteralInRegexp:
247
+ Enabled: true
248
+ Lint/BinaryOperatorWithIdenticalOperands:
249
+ Enabled: true
250
+ Lint/ConstantDefinitionInBlock:
251
+ Enabled: true
252
+ Lint/ConstantOverwrittenInRescue:
253
+ Enabled: true
254
+ Lint/ConstantReassignment:
255
+ Enabled: true
256
+ Lint/CopDirectiveSyntax:
257
+ Enabled: true
258
+ Lint/DeprecatedConstants:
259
+ Enabled: true
260
+ Lint/DeprecatedOpenSSLConstant:
261
+ Enabled: false
262
+ Lint/DuplicateBranch:
263
+ Enabled: true
264
+ Lint/DuplicateElsifCondition:
265
+ Enabled: true
266
+ Lint/DuplicateMagicComment:
267
+ Enabled: true
268
+ Lint/DuplicateMatchPattern:
269
+ Enabled: true
270
+ Lint/DuplicateRegexpCharacterClassElement:
271
+ Enabled: true
272
+ Lint/DuplicateRequire:
273
+ Enabled: true
274
+ Lint/DuplicateRescueException:
275
+ Enabled: true
276
+ Lint/DuplicateSetElement:
277
+ Enabled: true
278
+ Lint/EmptyBlock:
279
+ Enabled: false
280
+ Lint/EmptyClass:
281
+ Enabled: true
282
+ AllowComments: true
283
+ Lint/EmptyConditionalBody:
284
+ Enabled: true
285
+ Lint/EmptyFile:
286
+ Enabled: true
287
+ Lint/EmptyInPattern:
288
+ Enabled: true
289
+ AllowComments: true
290
+ Lint/FloatComparison:
291
+ Enabled: true
292
+ Lint/HashNewWithKeywordArgumentsAsDefault:
293
+ Enabled: true
294
+ Lint/IdentityComparison:
295
+ Enabled: true
296
+ Lint/IncompatibleIoSelectWithFiberScheduler:
297
+ Enabled: true
298
+ Lint/ItWithoutArgumentsInBlock:
299
+ Enabled: true
300
+ Lint/LambdaWithoutLiteralBlock:
301
+ Enabled: true
302
+ Lint/LiteralAssignmentInCondition:
303
+ Enabled: true
304
+ Lint/MissingSuper:
305
+ Enabled: false
306
+ Lint/MixedCaseRange:
307
+ Enabled: true
308
+ Lint/NoReturnInBeginEndBlocks:
309
+ Enabled: true
310
+ Lint/NonAtomicFileOperation:
311
+ Enabled: true
312
+ Lint/NumberedParameterAssignment:
313
+ Enabled: true
314
+ Lint/NumericOperationWithConstantResult:
315
+ Enabled: true
316
+ Lint/OrAssignmentToConstant:
317
+ Enabled: true
318
+ Lint/RaiseException:
319
+ Enabled: true
320
+ Lint/RedundantDirGlobSort:
321
+ Enabled: true
322
+ Lint/RedundantRegexpQuantifiers:
323
+ Enabled: true
324
+ Lint/RedundantSafeNavigation:
325
+ Enabled: true
326
+ Lint/RedundantTypeConversion:
327
+ Enabled: true
328
+ Lint/RefinementImportMethods:
329
+ Enabled: true
330
+ Lint/RequireRangeParentheses:
331
+ Enabled: true
332
+ Lint/RequireRelativeSelfPath:
333
+ Enabled: true
334
+ Lint/SelfAssignment:
335
+ Enabled: true
336
+ Lint/SharedMutableDefault:
337
+ Enabled: true
338
+ Lint/StructNewOverride:
339
+ Enabled: true
340
+ Lint/SuppressedExceptionInNumberConversion:
341
+ Enabled: true
342
+ Lint/SymbolConversion:
343
+ Enabled: true
344
+ EnforcedStyle: strict
345
+ Lint/ToEnumArguments:
346
+ Enabled: true
347
+ Lint/TrailingCommaInAttributeDeclaration:
348
+ Enabled: true
349
+ Lint/TripleQuotes:
350
+ Enabled: true
351
+ Lint/UnescapedBracketInRegexp:
352
+ Enabled: true
353
+ Lint/UnexpectedBlockArity:
354
+ Enabled: true
355
+ Lint/UnmodifiedReduceAccumulator:
356
+ Enabled: true
357
+ Lint/UnreachableLoop:
358
+ Enabled: true
359
+ Lint/UselessConstantScoping:
360
+ Enabled: true
361
+ Lint/UselessDefined:
362
+ Enabled: true
363
+ Lint/UselessMethodDefinition:
364
+ Enabled: true
365
+ Lint/UselessNumericOperation:
366
+ Enabled: true
367
+ Lint/UselessRescue:
368
+ Enabled: true
369
+ Lint/UselessRuby2Keywords:
370
+ Enabled: true
371
+
372
+ # Bundler
373
+ Bundler/OrderedGems:
374
+ Enabled: true
375
+
376
+ # Gemspec
377
+ Gemspec/AddRuntimeDependency:
378
+ Enabled: true
379
+ Gemspec/DeprecatedAttributeAssignment:
380
+ Enabled: false
381
+ Gemspec/DevelopmentDependencies:
382
+ Enabled: false
383
+ Gemspec/RequireMFA:
384
+ Enabled: false
385
+
386
+ # Naming
387
+ Naming/BlockForwarding:
388
+ Enabled: true
389
+ EnforcedStyle: explicit
390
+ Naming/PredicateName:
391
+ Enabled: false
392
+
393
+ # Security
394
+ Security/CompoundHash:
395
+ Enabled: true
396
+ Security/IoMethods:
397
+ Enabled: true
398
+
399
+ Layout/HashAlignment:
400
+ EnforcedColonStyle: key
401
+ EnforcedHashRocketStyle: key
402
+
403
+ Layout/MultilineMethodCallIndentation:
404
+ EnforcedStyle: indented_relative_to_receiver
405
+
406
+ Layout/ArgumentAlignment:
407
+ EnforcedStyle: with_first_argument
408
+
409
+ Layout/BlockAlignment:
410
+ EnforcedStyleAlignWith: start_of_block # or 'start_of_line' or 'either'
411
+
412
+ Layout/ArrayAlignment:
413
+ EnforcedStyle: with_first_element
414
+
415
+ Layout/MultilineBlockLayout:
416
+ Enabled: true
417
+
418
+ Layout/EndAlignment:
419
+ EnforcedStyleAlignWith: keyword
data/CHANGELOG.md ADDED
@@ -0,0 +1,5 @@
1
+ ## [Unreleased]
2
+
3
+ ## [0.1.0] - 2025-03-12
4
+
5
+ - Initial release
@@ -0,0 +1,132 @@
1
+ # Contributor Covenant Code of Conduct
2
+
3
+ ## Our Pledge
4
+
5
+ We as members, contributors, and leaders pledge to make participation in our
6
+ community a harassment-free experience for everyone, regardless of age, body
7
+ size, visible or invisible disability, ethnicity, sex characteristics, gender
8
+ identity and expression, level of experience, education, socio-economic status,
9
+ nationality, personal appearance, race, caste, color, religion, or sexual
10
+ identity and orientation.
11
+
12
+ We pledge to act and interact in ways that contribute to an open, welcoming,
13
+ diverse, inclusive, and healthy community.
14
+
15
+ ## Our Standards
16
+
17
+ Examples of behavior that contributes to a positive environment for our
18
+ community include:
19
+
20
+ * Demonstrating empathy and kindness toward other people
21
+ * Being respectful of differing opinions, viewpoints, and experiences
22
+ * Giving and gracefully accepting constructive feedback
23
+ * Accepting responsibility and apologizing to those affected by our mistakes,
24
+ and learning from the experience
25
+ * Focusing on what is best not just for us as individuals, but for the overall
26
+ community
27
+
28
+ Examples of unacceptable behavior include:
29
+
30
+ * The use of sexualized language or imagery, and sexual attention or advances of
31
+ any kind
32
+ * Trolling, insulting or derogatory comments, and personal or political attacks
33
+ * Public or private harassment
34
+ * Publishing others' private information, such as a physical or email address,
35
+ without their explicit permission
36
+ * Other conduct which could reasonably be considered inappropriate in a
37
+ professional setting
38
+
39
+ ## Enforcement Responsibilities
40
+
41
+ Community leaders are responsible for clarifying and enforcing our standards of
42
+ acceptable behavior and will take appropriate and fair corrective action in
43
+ response to any behavior that they deem inappropriate, threatening, offensive,
44
+ or harmful.
45
+
46
+ Community leaders have the right and responsibility to remove, edit, or reject
47
+ comments, commits, code, wiki edits, issues, and other contributions that are
48
+ not aligned to this Code of Conduct, and will communicate reasons for moderation
49
+ decisions when appropriate.
50
+
51
+ ## Scope
52
+
53
+ This Code of Conduct applies within all community spaces, and also applies when
54
+ an individual is officially representing the community in public spaces.
55
+ Examples of representing our community include using an official email address,
56
+ posting via an official social media account, or acting as an appointed
57
+ representative at an online or offline event.
58
+
59
+ ## Enforcement
60
+
61
+ Instances of abusive, harassing, or otherwise unacceptable behavior may be
62
+ reported to the community leaders responsible for enforcement at
63
+ [INSERT CONTACT METHOD].
64
+ All complaints will be reviewed and investigated promptly and fairly.
65
+
66
+ All community leaders are obligated to respect the privacy and security of the
67
+ reporter of any incident.
68
+
69
+ ## Enforcement Guidelines
70
+
71
+ Community leaders will follow these Community Impact Guidelines in determining
72
+ the consequences for any action they deem in violation of this Code of Conduct:
73
+
74
+ ### 1. Correction
75
+
76
+ **Community Impact**: Use of inappropriate language or other behavior deemed
77
+ unprofessional or unwelcome in the community.
78
+
79
+ **Consequence**: A private, written warning from community leaders, providing
80
+ clarity around the nature of the violation and an explanation of why the
81
+ behavior was inappropriate. A public apology may be requested.
82
+
83
+ ### 2. Warning
84
+
85
+ **Community Impact**: A violation through a single incident or series of
86
+ actions.
87
+
88
+ **Consequence**: A warning with consequences for continued behavior. No
89
+ interaction with the people involved, including unsolicited interaction with
90
+ those enforcing the Code of Conduct, for a specified period of time. This
91
+ includes avoiding interactions in community spaces as well as external channels
92
+ like social media. Violating these terms may lead to a temporary or permanent
93
+ ban.
94
+
95
+ ### 3. Temporary Ban
96
+
97
+ **Community Impact**: A serious violation of community standards, including
98
+ sustained inappropriate behavior.
99
+
100
+ **Consequence**: A temporary ban from any sort of interaction or public
101
+ communication with the community for a specified period of time. No public or
102
+ private interaction with the people involved, including unsolicited interaction
103
+ with those enforcing the Code of Conduct, is allowed during this period.
104
+ Violating these terms may lead to a permanent ban.
105
+
106
+ ### 4. Permanent Ban
107
+
108
+ **Community Impact**: Demonstrating a pattern of violation of community
109
+ standards, including sustained inappropriate behavior, harassment of an
110
+ individual, or aggression toward or disparagement of classes of individuals.
111
+
112
+ **Consequence**: A permanent ban from any sort of public interaction within the
113
+ community.
114
+
115
+ ## Attribution
116
+
117
+ This Code of Conduct is adapted from the [Contributor Covenant][homepage],
118
+ version 2.1, available at
119
+ [https://www.contributor-covenant.org/version/2/1/code_of_conduct.html][v2.1].
120
+
121
+ Community Impact Guidelines were inspired by
122
+ [Mozilla's code of conduct enforcement ladder][Mozilla CoC].
123
+
124
+ For answers to common questions about this code of conduct, see the FAQ at
125
+ [https://www.contributor-covenant.org/faq][FAQ]. Translations are available at
126
+ [https://www.contributor-covenant.org/translations][translations].
127
+
128
+ [homepage]: https://www.contributor-covenant.org
129
+ [v2.1]: https://www.contributor-covenant.org/version/2/1/code_of_conduct.html
130
+ [Mozilla CoC]: https://github.com/mozilla/diversity
131
+ [FAQ]: https://www.contributor-covenant.org/faq
132
+ [translations]: https://www.contributor-covenant.org/translations
data/LICENSE.txt ADDED
@@ -0,0 +1,21 @@
1
+ The MIT License (MIT)
2
+
3
+ Copyright (c) 2025 gregoryrivage
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,119 @@
1
+ # Hooksmith
2
+
3
+ **Hooksmith** is a modular, Rails-friendly gem for processing webhooks. It allows you to register multiple processors for different providers and events, ensuring that only one processor handles a given payload. If multiple processors qualify, an error is raised to avoid ambiguous behavior.
4
+
5
+ ## Features
6
+
7
+ - **DSL for Registration:** Group processors by provider and event.
8
+ - **Flexible Dispatcher:** Dynamically selects the appropriate processor based on payload conditions.
9
+ - **Rails Integration:** Automatically configures with Rails using a Railtie.
10
+ - **Lightweight Logging:** Built-in logging that can be switched to `Rails.logger` when in a Rails environment.
11
+ - **Tested with Minitest:** 100% branch coverage for robust behavior.
12
+
13
+ ## Installation
14
+
15
+ Add this line to your application's Gemfile:
16
+
17
+ ```ruby
18
+ gem 'hooksmith', '~> 0.1.0'
19
+ ```
20
+
21
+ Then execute:
22
+ ```bash
23
+ bundle install
24
+ ```
25
+
26
+ Or install it yourself as:
27
+
28
+ ```bash
29
+ gem install hooksmith
30
+ ```
31
+
32
+ ## Usage
33
+
34
+ ### Configuration
35
+
36
+ Configure your webhook processors in an initializer (e.g., `config/initializers/hooksmith.rb`):
37
+
38
+ ```ruby
39
+ Hooksmith.configure do |config|
40
+ config.provider(:stripe) do |stripe|
41
+ stripe.register(:charge_succeeded, Stripe::Processor::ChargeSucceeded::Tenant)
42
+ stripe.register(:charge_succeeded, Stripe::Processor::ChargeSucceeded::Landlord)
43
+ end
44
+
45
+ config.provider(:paypal) do |paypal|
46
+ paypal.register(:payment_received, Paypal::Processor::PaymentReceived)
47
+ end
48
+ end
49
+ ```
50
+
51
+ ## Implementing a Processor
52
+ Create a processor by inheriting from `Hooksmith::Processor::Base`:
53
+
54
+ ```ruby
55
+ module Stripe
56
+ module Processor
57
+ module ChargeSucceeded
58
+ class Tenant < Hooksmith::Processor::Base
59
+ # Only handle events with a tenant_payment_id.
60
+ def can_handle?(payload)
61
+ payload.dig("metadata", "tenant_payment_id").present?
62
+ end
63
+
64
+ def process!
65
+ tenant_payment_id = payload.dig("metadata", "tenant_payment_id")
66
+ # Add your business logic here (e.g., update database records).
67
+ puts "Processed tenant payment: #{tenant_payment_id}"
68
+ end
69
+ end
70
+ end
71
+ end
72
+ end
73
+ ```
74
+
75
+ ## Dispatching a Webhook
76
+
77
+ Use the dispatcher in your webhook controller:
78
+
79
+ ```ruby
80
+ class WebhooksController < ApplicationController
81
+ skip_before_action :verify_authenticity_token
82
+
83
+ def receive
84
+ provider = params[:provider] || "stripe"
85
+ event = params[:event] || "charge_succeeded"
86
+ payload = params[:data] # Adjust extraction as needed
87
+
88
+ Hooksmith::Dispatcher.new(provider: provider, event: event, payload: payload).run!
89
+ head :ok
90
+ rescue Hooksmith::MultipleProcessorsError => e
91
+ render json: { error: e.message }, status: :unprocessable_entity
92
+ rescue StandardError => e
93
+ render json: { error: e.message }, status: :internal_server_error
94
+ end
95
+ end
96
+ ```
97
+
98
+ ## Testing
99
+ The gem includes a full test suite using Minitest with 100% branch coverage. See the test/ directory for examples. You can run the tests with:
100
+
101
+ ```
102
+ bundle exec rake test
103
+ ```
104
+
105
+ If you want to check test coverage, you can integrate SimpleCov by adding the following at the top of your test/test_helper.rb:
106
+
107
+ ```ruby
108
+ require "simplecov"
109
+ SimpleCov.start
110
+ ```
111
+
112
+ Then run the tests to generate a coverage report.
113
+
114
+ ## Contributing
115
+ Bug reports and pull requests are welcome on GitHub at https://github.com/gregorypreve/hooksmith.
116
+
117
+
118
+ ## License
119
+ The gem is available as open source under the terms of the MIT License.
data/Rakefile ADDED
@@ -0,0 +1,12 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'bundler/gem_tasks'
4
+ require 'minitest/test_task'
5
+
6
+ Minitest::TestTask.create
7
+
8
+ require 'rubocop/rake_task'
9
+
10
+ RuboCop::RakeTask.new
11
+
12
+ task default: %i[test rubocop]
@@ -0,0 +1,65 @@
1
+ # frozen_string_literal: true
2
+
3
+ # Provides a DSL for registering webhook processors by provider and event.
4
+ #
5
+ module Hooksmith
6
+ # Configuration holds the registry of all processors.
7
+ class Configuration
8
+ # @return [Hash] a registry mapping provider symbols to arrays of processor entries.
9
+ attr_reader :registry
10
+
11
+ def initialize
12
+ # Registry structure: { provider_symbol => [{ event: event_symbol, processor: ProcessorClass }, ...] }
13
+ @registry = Hash.new { |hash, key| hash[key] = [] }
14
+ end
15
+
16
+ # Groups registrations under a specific provider.
17
+ #
18
+ # @param provider_name [Symbol, String] the provider name (e.g., :stripe)
19
+ # @yield [ProviderConfig] a block yielding a ProviderConfig object
20
+ def provider(provider_name)
21
+ provider_config = ProviderConfig.new(provider_name)
22
+ yield(provider_config)
23
+ registry[provider_name.to_sym].concat(provider_config.entries)
24
+ end
25
+
26
+ # Direct registration of a processor.
27
+ #
28
+ # @param provider [Symbol, String] the provider name
29
+ # @param event [Symbol, String] the event name
30
+ # @param processor_class [Class] the processor class
31
+ def register_processor(provider, event, processor_class)
32
+ registry[provider.to_sym] << { event: event.to_sym, processor: processor_class }
33
+ end
34
+
35
+ # Returns all processor entries for a given provider and event.
36
+ #
37
+ # @param provider [Symbol, String] the provider name
38
+ # @param event [Symbol, String] the event name
39
+ # @return [Array<Hash>] the array of matching entries.
40
+ def processors_for(provider, event)
41
+ registry[provider.to_sym].select { |entry| entry[:event] == event.to_sym }
42
+ end
43
+ end
44
+
45
+ # ProviderConfig is used internally by the DSL to collect processor registrations.
46
+ class ProviderConfig
47
+ # @return [Symbol, String] the provider name.
48
+ attr_reader :provider
49
+ # @return [Array<Hash>] list of entries registered.
50
+ attr_reader :entries
51
+
52
+ def initialize(provider)
53
+ @provider = provider
54
+ @entries = []
55
+ end
56
+
57
+ # Registers a processor for a specific event.
58
+ #
59
+ # @param event [Symbol, String] the event name.
60
+ # @param processor_class [Class] the processor class.
61
+ def register(event, processor_class)
62
+ entries << { event: event.to_sym, processor: processor_class }
63
+ end
64
+ end
65
+ end
@@ -0,0 +1,67 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Hooksmith
4
+ # Dispatcher routes incoming webhook payloads to the appropriate processor.
5
+ #
6
+ # @example Dispatch a webhook event:
7
+ # Hooksmith::Dispatcher.new(provider: :stripe, event: :charge_succeeded, payload: payload).run!
8
+ #
9
+ class Dispatcher
10
+ # Initializes a new Dispatcher.
11
+ #
12
+ # @param provider [Symbol, String] the provider (e.g., :stripe)
13
+ # @param event [Symbol, String] the event (e.g., :charge_succeeded)
14
+ # @param payload [Hash] the webhook payload data.
15
+ def initialize(provider:, event:, payload:)
16
+ @provider = provider.to_sym
17
+ @event = event.to_sym
18
+ @payload = payload
19
+ end
20
+
21
+ # Runs the dispatcher.
22
+ #
23
+ # Instantiates each processor registered for the given provider and event,
24
+ # then selects the ones that can handle the payload using the can_handle? method.
25
+ # - If no processors qualify, logs a warning.
26
+ # - If more than one qualifies, raises MultipleProcessorsError.
27
+ # - Otherwise, processes the event with the single matching processor.
28
+ #
29
+ # @raise [MultipleProcessorsError] if multiple processors qualify.
30
+ def run!
31
+ # Fetch all processors registered for this provider and event.
32
+ entries = Hooksmith.configuration.processors_for(@provider, @event)
33
+
34
+ # Instantiate each processor and filter by condition.
35
+ matching_processors = entries.map do |entry|
36
+ processor = entry[:processor].new(@payload)
37
+ processor if processor.can_handle?(@payload)
38
+ end.compact
39
+
40
+ if matching_processors.empty?
41
+ Hooksmith.logger.warn("No processor registered for #{@provider} event #{@event} could handle the payload")
42
+ return
43
+ end
44
+
45
+ # If more than one processor qualifies, raise an error.
46
+ raise MultipleProcessorsError.new(@provider, @event, @payload) if matching_processors.size > 1
47
+
48
+ # Exactly one matching processor.
49
+ matching_processors.first.process!
50
+ rescue StandardError => e
51
+ Hooksmith.logger.error("Error processing #{@provider} event #{@event}: #{e.message}")
52
+ raise e
53
+ end
54
+ end
55
+
56
+ # Raised when multiple processors can handle the same event.
57
+ class MultipleProcessorsError < StandardError
58
+ # Initializes the error with details about the provider, event, and payload.
59
+ #
60
+ # @param provider [Symbol] the provider name.
61
+ # @param event [Symbol] the event name.
62
+ # @param payload [Hash] the webhook payload.
63
+ def initialize(provider, event, payload)
64
+ super("Multiple processors found for #{provider} event #{event}. Payload: #{payload}")
65
+ end
66
+ end
67
+ end
@@ -0,0 +1,47 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'logger'
4
+ require 'singleton'
5
+
6
+ module Hooksmith
7
+ # A lightweight logger for Hooksmith.
8
+ #
9
+ # Uses Ruby's standard Logger under the hood and can be configured to use Rails.logger.
10
+ class Logger
11
+ include Singleton
12
+
13
+ # Initializes the logger.
14
+ def initialize
15
+ @logger = ::Logger.new($stdout)
16
+ @logger.level = ::Logger::INFO
17
+ end
18
+
19
+ # Logs an info message.
20
+ #
21
+ # @param msg [String] the message.
22
+ def info(msg)
23
+ @logger.info(msg)
24
+ end
25
+
26
+ # Logs a warning message.
27
+ #
28
+ # @param msg [String] the message.
29
+ def warn(msg)
30
+ @logger.warn(msg)
31
+ end
32
+
33
+ # Logs an error message.
34
+ #
35
+ # @param msg [String] the message.
36
+ def error(msg)
37
+ @logger.error(msg)
38
+ end
39
+
40
+ # Logs a debug message.
41
+ #
42
+ # @param msg [String] the message.
43
+ def debug(msg)
44
+ @logger.debug(msg)
45
+ end
46
+ end
47
+ end
@@ -0,0 +1,39 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Hooksmith
4
+ module Processor
5
+ # Base class for all webhook processors.
6
+ #
7
+ # Processors should inherit from this class and implement the process! method.
8
+ #
9
+ # @abstract
10
+ class Base
11
+ # @return [Hash] the payload for the webhook.
12
+ attr_reader :payload
13
+
14
+ # Initializes the processor with a payload.
15
+ #
16
+ # @param payload [Hash] the webhook payload.
17
+ def initialize(payload)
18
+ @payload = payload
19
+ end
20
+
21
+ # Checks if the processor can handle the payload.
22
+ # Override this method in subclasses if conditional processing is needed.
23
+ #
24
+ # @param payload [Hash] the webhook payload.
25
+ # @return [Boolean] true if the processor can handle the payload.
26
+ def can_handle?(_payload)
27
+ true
28
+ end
29
+
30
+ # Process the webhook.
31
+ # Must be implemented by subclasses.
32
+ #
33
+ # @raise [NotImplementedError] if not implemented.
34
+ def process!
35
+ raise NotImplementedError, 'Implement process! in your processor'
36
+ end
37
+ end
38
+ end
39
+ end
@@ -0,0 +1,18 @@
1
+ # frozen_string_literal: true
2
+
3
+ if defined?(Rails)
4
+ module Hooksmith
5
+ # Railtie integration for Hooksmith.
6
+ #
7
+ # This file allows Hooksmith to integrate seamlessly with a Rails application.
8
+ class Railtie < Rails::Railtie
9
+ initializer 'hooksmith.configure_rails_initialization' do |_|
10
+ Hooksmith.logger.info('Hooksmith initialized in Rails')
11
+ # Optionally set the gem logger to use Rails.logger if available.
12
+ if defined?(Rails.logger) && Rails.logger
13
+ Hooksmith::Logger.instance.instance_variable_set(:@logger, Rails.logger)
14
+ end
15
+ end
16
+ end
17
+ end
18
+ end
@@ -0,0 +1,5 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Hooksmith
4
+ VERSION = '0.1.0'
5
+ end
data/lib/hooksmith.rb ADDED
@@ -0,0 +1,39 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'hooksmith/version'
4
+ require 'hooksmith/configuration'
5
+ require 'hooksmith/dispatcher'
6
+ require 'hooksmith/logger'
7
+ require 'hooksmith/processor/base'
8
+ require 'hooksmith/railtie' if defined?(Rails)
9
+
10
+ # Main entry point for the Hooksmith gem.
11
+ #
12
+ # @example Basic usage:
13
+ # Hooksmith.configure do |config|
14
+ # config.provider(:stripe) do |stripe|
15
+ # stripe.register(:charge_succeeded, MyStripeProcessor)
16
+ # end
17
+ # end
18
+ #
19
+ # Hooksmith::Dispatcher.new(provider: :stripe, event: :charge_succeeded, payload: payload).run!
20
+ #
21
+ module Hooksmith
22
+ # Returns the configuration instance.
23
+ # @return [Configuration] the configuration instance.
24
+ def self.configuration
25
+ @configuration ||= Configuration.new
26
+ end
27
+
28
+ # Yields the configuration to a block.
29
+ # @yieldparam config [Configuration]
30
+ def self.configure
31
+ yield(configuration)
32
+ end
33
+
34
+ # Returns the gem's logger instance.
35
+ # @return [Logger] the logger instance.
36
+ def self.logger
37
+ Logger.instance
38
+ end
39
+ end
data/sig/hooksmith.rbs ADDED
@@ -0,0 +1,4 @@
1
+ module Hooksmith
2
+ VERSION: String
3
+ # See the writing guide of rbs: https://github.com/ruby/rbs#guides
4
+ end
metadata ADDED
@@ -0,0 +1,59 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: hooksmith
3
+ version: !ruby/object:Gem::Version
4
+ version: 0.1.0
5
+ platform: ruby
6
+ authors:
7
+ - gregoryrivage
8
+ bindir: exe
9
+ cert_chain: []
10
+ date: 2025-03-12 00:00:00.000000000 Z
11
+ dependencies: []
12
+ description: Hooksmith is a gem that allows you to handle webhooks in your Rails application.
13
+ email:
14
+ - gregory@rivage.immo
15
+ executables: []
16
+ extensions: []
17
+ extra_rdoc_files: []
18
+ files:
19
+ - ".DS_Store"
20
+ - ".rubocop.yml"
21
+ - CHANGELOG.md
22
+ - CODE_OF_CONDUCT.md
23
+ - LICENSE.txt
24
+ - README.md
25
+ - Rakefile
26
+ - lib/hooksmith.rb
27
+ - lib/hooksmith/configuration.rb
28
+ - lib/hooksmith/dispatcher.rb
29
+ - lib/hooksmith/logger.rb
30
+ - lib/hooksmith/processor/base.rb
31
+ - lib/hooksmith/railtie.rb
32
+ - lib/hooksmith/version.rb
33
+ - sig/hooksmith.rbs
34
+ homepage: https://github.com/gregoryrivage/hooksmith
35
+ licenses:
36
+ - MIT
37
+ metadata:
38
+ allowed_push_host: https://rubygems.org
39
+ homepage_uri: https://github.com/gregoryrivage/hooksmith
40
+ source_code_uri: https://github.com/gregoryrivage/hooksmith
41
+ changelog_uri: https://github.com/gregoryrivage/hooksmith/blob/main/CHANGELOG.md
42
+ rdoc_options: []
43
+ require_paths:
44
+ - lib
45
+ required_ruby_version: !ruby/object:Gem::Requirement
46
+ requirements:
47
+ - - ">="
48
+ - !ruby/object:Gem::Version
49
+ version: 3.1.0
50
+ required_rubygems_version: !ruby/object:Gem::Requirement
51
+ requirements:
52
+ - - ">="
53
+ - !ruby/object:Gem::Version
54
+ version: '0'
55
+ requirements: []
56
+ rubygems_version: 3.6.2
57
+ specification_version: 4
58
+ summary: Hooksmith is a gem that allows you to handle webhooks in your Rails application.
59
+ test_files: []