monkey_bars 0.1.0.pre.pre

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: fc4ba27dfd0e854430540e31905974d75e4f37f297ff1ac54358f0d36b13d154
4
+ data.tar.gz: '0369347b930b2d800823ed47e1cd1771d7af1a9300181e397f48b39e17e00649'
5
+ SHA512:
6
+ metadata.gz: 0c5538b4c1268aa4fe8be82ce589b8151298d4ea2dc6a533227b5b2e2376e718a799fe003bfa7fffd813574ca58a087f5868f89eb76e30e8d083e545a7282ecc
7
+ data.tar.gz: 5a431c19c204c317090c7983ba9d76442c291d0c3a2b98c31be15defbee27e7b87c808681ff6b51ba431f5c4dfe51f8c889ce9e80acbad9afd6457bb969e46fa
@@ -0,0 +1,122 @@
1
+ ## Code of Conduct
2
+
3
+ This project follows the Contributor Covenant Code of Conduct.
4
+
5
+ ### Our Pledge
6
+
7
+ We as members, contributors, and leaders pledge to make participation in our
8
+ community a harassment-free experience for everyone, regardless of age, body
9
+ size, visible or invisible disability, ethnicity, sex characteristics, gender
10
+ identity and expression, level of experience, education, socio-economic status,
11
+ nationality, personal appearance, race, caste, color, religion, or sexual
12
+ identity and orientation.
13
+
14
+ We pledge to act and interact in ways that contribute to an open, welcoming,
15
+ diverse, inclusive, and healthy community.
16
+
17
+ ### Our Standards
18
+
19
+ Examples of behavior that contributes to a positive environment for our
20
+ community include:
21
+
22
+ - Demonstrating empathy and kindness toward other people
23
+ - Being respectful of differing opinions, viewpoints, and experiences
24
+ - Giving and gracefully accepting constructive feedback
25
+ - Accepting responsibility and apologizing to those affected by our mistakes,
26
+ and learning from the experience
27
+ - Focusing on what is best not just for us as individuals, but for the overall
28
+ community
29
+
30
+ Examples of unacceptable behavior include:
31
+
32
+ - The use of sexualized language or imagery, and sexual attention or advances
33
+ - Trolling, insulting or derogatory comments, and personal or political attacks
34
+ - Public or private harassment
35
+ - Publishing others' private information, such as a physical or email address,
36
+ without their explicit permission
37
+ - Other conduct which could reasonably be considered inappropriate in a
38
+ professional setting
39
+
40
+ ### Enforcement Responsibilities
41
+
42
+ Community leaders are responsible for clarifying and enforcing our standards of
43
+ acceptable behavior and will take appropriate and fair corrective action in
44
+ response to any behavior that they deem inappropriate, threatening, offensive,
45
+ or harmful.
46
+
47
+ Community leaders have the right and responsibility to remove, edit, or reject
48
+ comments, commits, code, wiki edits, issues, and other contributions that are
49
+ not aligned to this Code of Conduct, and will communicate reasons for moderation
50
+ decisions when appropriate.
51
+
52
+ ### Scope
53
+
54
+ This Code of Conduct applies within all community spaces, and also applies when
55
+ an individual is officially representing the community in public spaces.
56
+ Examples of representing our community include using an official email address,
57
+ posting via an official social media account, or acting as an appointed
58
+ representative at an online or offline event.
59
+
60
+ ### Enforcement
61
+
62
+ Instances of abusive, harassing, or otherwise unacceptable behavior may be
63
+ reported to the community leaders responsible for enforcement at
64
+ afrojas@gmail.com. All complaints will be reviewed and investigated promptly
65
+ and fairly.
66
+
67
+ All community leaders are obligated to respect the privacy and security of the
68
+ reporter of any incident.
69
+
70
+ ### Enforcement Guidelines
71
+
72
+ Community leaders will follow these Community Impact Guidelines in determining
73
+ the consequences for any action they deem in violation of this Code of Conduct:
74
+
75
+ #### 1. Correction
76
+
77
+ **Community Impact**: Use of inappropriate language or other behavior deemed
78
+ unprofessional or unwelcome in the community.
79
+
80
+ **Consequence**: A private, written warning from community leaders, providing
81
+ clarity around the nature of the violation and an explanation of why the
82
+ behavior was inappropriate. A public apology may be requested.
83
+
84
+ #### 2. Warning
85
+
86
+ **Community Impact**: A violation through a single incident or series of
87
+ actions.
88
+
89
+ **Consequence**: A warning with consequences for continued behavior. No
90
+ interaction with the people involved, including unsolicited interaction with
91
+ those enforcing the Code of Conduct, for a specified period of time. This
92
+ includes avoiding interactions in community spaces as well as external channels
93
+ like social media. Violating these terms may lead to a temporary or permanent
94
+ ban.
95
+
96
+ #### 3. Temporary Ban
97
+
98
+ **Community Impact**: A serious violation of community standards, including
99
+ sustained inappropriate behavior.
100
+
101
+ **Consequence**: A temporary ban from any sort of interaction or public
102
+ communication with the community for a specified period of time. No public or
103
+ private interaction with the people involved, including unsolicited interaction
104
+ with those enforcing the Code of Conduct, is allowed during this period.
105
+ Violating these terms may lead to a permanent ban.
106
+
107
+ #### 4. Permanent Ban
108
+
109
+ **Community Impact**: Demonstrating a pattern of violation of community
110
+ standards, including sustained inappropriate behavior, harassment of an
111
+ individual, or aggression toward or disparagement of classes of individuals.
112
+
113
+ **Consequence**: A permanent ban from any sort of public interaction within the
114
+ community.
115
+
116
+ ### Attribution
117
+
118
+ This Code of Conduct is adapted from the Contributor Covenant, version 2.1,
119
+ available at https://www.contributor-covenant.org/version/2/1/code_of_conduct.html
120
+
121
+ Community Impact Guidelines were inspired by
122
+ https://www.contributor-covenant.org/version/2/1/code_of_conduct.html#enforcement-guidelines
data/CONTRIBUTING.md ADDED
@@ -0,0 +1,25 @@
1
+ ## Contributing
2
+
3
+ Thanks for taking the time to contribute!
4
+
5
+ ### Reporting issues
6
+
7
+ - Search existing issues before opening a new one.
8
+ - Include a minimal reproduction, Ruby version, and gem version.
9
+
10
+ ### Development setup
11
+
12
+ - Install dependencies: `bundle install`
13
+ - Run tests: `bundle exec rspec`
14
+ - Run formatting: `bundle exec standardrb`
15
+ - Ensure it works across all versions with `bin/docker-test --all`
16
+
17
+ ### Pull requests
18
+
19
+ - Keep changes focused and small.
20
+ - Add or update tests for behavior changes.
21
+ - Update documentation and examples when relevant.
22
+ - Run the test suite and formatter before submitting.
23
+
24
+ By participating, you agree to follow the code of conduct in
25
+ `CODE_OF_CONDUCT.md`.
data/LICENSE.txt ADDED
@@ -0,0 +1,22 @@
1
+ The MIT License (MIT)
2
+
3
+ Copyright (c) 2026 Andrés Rojas
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.
22
+
data/README.md ADDED
@@ -0,0 +1,224 @@
1
+ # MonkeyBars
2
+
3
+ Safe, version-aware monkey patching for Ruby modules and classes. MonkeyBars
4
+ gives you a structured DSL to add or override methods and constants while
5
+ verifying the target's version and validating method arity.
6
+
7
+ ## But... why?
8
+
9
+ Monkey patching is sometimes necessary, but it is easy to get wrong. This gem
10
+ adds guardrails so patches fail loudly when:
11
+
12
+ - The target module/class is missing
13
+ - The target version is not what you expect
14
+ - You try to add a method/constant that already exists
15
+ - You try to patch a method/constant that does not exist
16
+ - Method arity changes unexpectedly
17
+
18
+ ## Installation
19
+
20
+ Add to your Gemfile:
21
+
22
+ ```ruby
23
+ gem "monkey_bars"
24
+ ```
25
+
26
+ Or install directly:
27
+
28
+ ```sh
29
+ gem install monkey_bars
30
+ ```
31
+
32
+ Requires Ruby 3.2+.
33
+
34
+ ## Quick start
35
+
36
+ Create a patcher class and extend `MonkeyBars`, then call the appropriate
37
+ methods:
38
+
39
+ ```ruby
40
+ class MyPatch
41
+ extend MonkeyBars
42
+
43
+ patch(SomeLibrary, version: "2.3.1", version_check: -> { SomeLibrary::VERSION }) do
44
+ new_instance_methods do
45
+ def new_method
46
+ "added"
47
+ end
48
+ end
49
+ end
50
+ end
51
+ ```
52
+
53
+ ## LLM usage guide
54
+
55
+ If you want LLM-friendly, structured guidance for patching, see:
56
+
57
+ - `docs/llm-usage.md`
58
+
59
+ ## Core DSL
60
+
61
+ The patcher is a class or module that `extend`s `MonkeyBars`. Patches are
62
+ declared inside a block and then applied with `patch` (immediately) or
63
+ `prepare_for_patching` + `patch!` (deferred).
64
+
65
+ ### Patch entry points
66
+
67
+ - `patch(monkey, version:, version_check:)` applies immediately
68
+ - `prepare_for_patching(monkey, version:, version_check:)` prepares a patch
69
+ - `patch!` applies a prepared patch
70
+
71
+ If `patch!` runs without any methods or constants defined, it emits a warning.
72
+
73
+ The `monkey` can be:
74
+
75
+ - A module/class reference
76
+ - A string constant name (resolved with `Kernel.const_get`)
77
+ - A lambda/proc that returns a module/class
78
+
79
+ ### Patch blocks
80
+
81
+ Use these block helpers to describe changes:
82
+
83
+ - `patch_instance_methods` to override existing instance methods
84
+ - `new_instance_methods` to add new instance methods
85
+ - `patch_class_methods` to override existing class methods
86
+ - `new_class_methods` to add new class methods
87
+ - `patch_constants` to redefine existing constants
88
+ - `new_constants` to add new constants
89
+ - `post_patch` to run after patching (with 0 or 1 arg)
90
+
91
+ You can call any of these helpers multiple times; MonkeyBars will combine them.
92
+ This is helpful when you want to ignore some arity check errors (see below) for
93
+ some methods but not others.
94
+
95
+ ### Method arity checks
96
+
97
+ When patching existing methods, arity must match by default. You can opt out:
98
+
99
+ ```ruby
100
+ patch_instance_methods(ignore_arity_errors: true) do
101
+ def method_with_args(*args)
102
+ args.sum
103
+ end
104
+ end
105
+ ```
106
+
107
+ ### super_super helper
108
+
109
+ If you're looking to mimic fully replacing an existing method and need to call
110
+ `super`, meaning, you want to 'skip' over the original implementation you are
111
+ patching on top of, you can include this helper which exposes a `#super_super`
112
+ method that does just that.
113
+
114
+ ```ruby
115
+ class A
116
+ VERSION = "1.0"
117
+
118
+ def cut_out_the_middlemane
119
+ puts "A#cut_out_the_middlemane"
120
+ end
121
+ end
122
+
123
+ class B < A
124
+ def cut_out_the_middlemane
125
+ puts "B#cut_out_the_middlemane"
126
+ super
127
+ end
128
+ end
129
+
130
+ class BPatcher
131
+ extend MonkeyBars
132
+
133
+ patch(B, version: "1.0", version_check: -> { B::VERSION }) do
134
+ patch_instance_methods(include_super_super: true) do
135
+ def cut_out_the_middlemane
136
+ puts "BPatcher#cut_out_the_middlemane"
137
+ super_super
138
+ end
139
+ end
140
+ end
141
+ end
142
+
143
+ # B.new.cut_out_the_middlemane
144
+ # => BPatcher#cut_out_the_middlemane
145
+ # => A#cut_out_the_middlemane
146
+ ```
147
+
148
+ The same option is available for class methods.
149
+
150
+ ## Example: full patch
151
+
152
+ ```ruby
153
+ class IntegrationPatch
154
+ extend MonkeyBars
155
+
156
+ patch("SomeLibrary", version: "1.0.0", version_check: -> { SomeLibrary::VERSION }) do
157
+ new_class_methods do
158
+ def new_class_method
159
+ "new class"
160
+ end
161
+ end
162
+
163
+ patch_class_methods do
164
+ def class_method
165
+ super + " + modified"
166
+ end
167
+ end
168
+
169
+ new_instance_methods do
170
+ def new_instance_method
171
+ "new instance"
172
+ end
173
+ end
174
+
175
+ patch_instance_methods do
176
+ def instance_method
177
+ super + " + modified"
178
+ end
179
+ end
180
+
181
+ patch_constants do
182
+ const_set(:TIMEOUT, 60)
183
+ end
184
+
185
+ new_constants do
186
+ const_set(:MAX_RETRIES, 5)
187
+ end
188
+
189
+ post_patch do |monkey|
190
+ # optional callback
191
+ end
192
+ end
193
+
194
+ end
195
+ ```
196
+
197
+ ## Errors you may see
198
+
199
+ MonkeyBars raises specific errors to keep patches safe and explicit:
200
+
201
+ - `MonkeyBars::NoPatchableMonkeyFoundError`
202
+ - `MonkeyBars::NoPatchableVersionCheckError`
203
+ - `MonkeyBars::NoPatchableVersionFoundError`
204
+ - `MonkeyBars::NoPatchableInstanceMethodFoundError`
205
+ - `MonkeyBars::NoPatchableClassMethodFoundError`
206
+ - `MonkeyBars::MismatchedInstanceMethodArityError`
207
+ - `MonkeyBars::MismatchedClassMethodArityError`
208
+ - `MonkeyBars::NewInstanceMethodAlreadyExistsError`
209
+ - `MonkeyBars::NewClassMethodAlreadyExistsError`
210
+ - `MonkeyBars::PatchConstantNotFoundError`
211
+ - `MonkeyBars::NewConstantAlreadyExistsError`
212
+ - `MonkeyBars::PatchAlreadyPerformedError`
213
+
214
+ ## Development
215
+
216
+ ```sh
217
+ bin/setup
218
+ bin/console
219
+ bundle exec rspec
220
+ ```
221
+
222
+ ## License
223
+
224
+ MIT. See `LICENSE.txt`.
data/docs/llm-usage.md ADDED
@@ -0,0 +1,232 @@
1
+ # LLM Usage Guide for MonkeyBars
2
+
3
+ This guide is written for LLMs and tools that need precise instructions to
4
+ apply patches safely with MonkeyBars. It focuses on the public API, expected
5
+ inputs/outputs, and common failure modes.
6
+
7
+ ## Quick start
8
+
9
+ Minimal, correct patch that adds a new instance method:
10
+
11
+ ```ruby
12
+ class MyPatch
13
+ extend MonkeyBars
14
+
15
+ patch(SomeLibrary, version: "2.3.1", version_check: -> { SomeLibrary::VERSION }) do
16
+ new_instance_methods do
17
+ def new_method
18
+ "added"
19
+ end
20
+ end
21
+ end
22
+ end
23
+ ```
24
+
25
+ ## Core concepts
26
+
27
+ ### Monkey resolution
28
+
29
+ The `monkey` argument can be:
30
+
31
+ - A module/class reference (e.g. `SomeLibrary`)
32
+ - A string constant name (e.g. `"SomeLibrary"`, resolved via `Kernel.const_get`)
33
+ - A lambda/proc that returns a module/class (evaluated at patch time)
34
+
35
+ If it cannot be resolved, `MonkeyBars::NoPatchableMonkeyFoundError` is raised.
36
+
37
+ ### Version checking
38
+
39
+ `version_check` must be callable and return the current version. MonkeyBars
40
+ compares it with `version` using exact equality. Mismatches raise
41
+ `MonkeyBars::NoPatchableVersionFoundError`.
42
+
43
+ ### Patch lifecycle
44
+
45
+ - `patch(...)` validates and applies immediately.
46
+ - `prepare_for_patching(...)` validates and stores the patch.
47
+ - `patch!` applies a previously prepared patch and can only be called once.
48
+
49
+ Calling `patch!` more than once raises `MonkeyBars::PatchAlreadyPerformedError`.
50
+
51
+ ## API reference
52
+
53
+ ### Entry points
54
+
55
+ #### `patch(monkey, version:, version_check:)`
56
+
57
+ Validates and applies a patch immediately.
58
+
59
+ - `monkey`: module/class, string, or callable
60
+ - `version`: expected version (exact string match)
61
+ - `version_check`: callable returning current version
62
+ - Side effect: mutates the target module/class in place
63
+
64
+ #### `prepare_for_patching(monkey, version:, version_check:)`
65
+
66
+ Validates and stores patch definitions for later application.
67
+
68
+ #### `patch!`
69
+
70
+ Applies a prepared patch exactly once.
71
+
72
+ ### Patch blocks (helpers)
73
+
74
+ Each helper can be called multiple times; MonkeyBars combines the definitions.
75
+
76
+ #### `new_instance_methods(&block)`
77
+
78
+ Adds new instance methods via `include`.
79
+
80
+ - Error: `MonkeyBars::NewInstanceMethodAlreadyExistsError` if method exists.
81
+
82
+ #### `patch_instance_methods(ignore_arity_errors: false, include_super_super: false, &block)`
83
+
84
+ Overrides existing instance methods via `prepend`.
85
+
86
+ - Error: `MonkeyBars::NoPatchableInstanceMethodFoundError` if method does not exist.
87
+ - Error: `MonkeyBars::MismatchedInstanceMethodArityError` when arity differs,
88
+ unless `ignore_arity_errors: true` is set.
89
+ - `include_super_super: true` makes `#super_super` available for these methods.
90
+
91
+ #### `new_class_methods(&block)`
92
+
93
+ Adds new class methods via `extend`.
94
+
95
+ - Error: `MonkeyBars::NewClassMethodAlreadyExistsError` if method exists.
96
+
97
+ #### `patch_class_methods(ignore_arity_errors: false, include_super_super: false, &block)`
98
+
99
+ Overrides existing class methods via `singleton_class.prepend`.
100
+
101
+ - Error: `MonkeyBars::NoPatchableClassMethodFoundError` if method does not exist.
102
+ - Error: `MonkeyBars::MismatchedClassMethodArityError` when arity differs,
103
+ unless `ignore_arity_errors: true` is set.
104
+ - `include_super_super: true` makes `#super_super` available for these methods.
105
+
106
+ #### `patch_constants(&block)`
107
+
108
+ Redefines existing constants (remove + set).
109
+
110
+ - Error: `MonkeyBars::PatchConstantNotFoundError` if constant does not exist.
111
+
112
+ #### `new_constants(&block)`
113
+
114
+ Adds new constants.
115
+
116
+ - Error: `MonkeyBars::NewConstantAlreadyExistsError` if constant exists.
117
+
118
+ #### `post_patch(&block)`
119
+
120
+ Optional callback after patching. If the block arity is:
121
+
122
+ - `0`: called with no args
123
+ - `1`: called with the patched module/class
124
+
125
+ ## Examples
126
+
127
+ ### Patch an existing instance method
128
+
129
+ ```ruby
130
+ class FixPatch
131
+ extend MonkeyBars
132
+
133
+ patch(SomeLibrary, version: "1.0.0", version_check: -> { SomeLibrary::VERSION }) do
134
+ patch_instance_methods do
135
+ def compute(value)
136
+ super(value) + 1
137
+ end
138
+ end
139
+ end
140
+ end
141
+ ```
142
+
143
+ ### Add new class method and constant
144
+
145
+ ```ruby
146
+ class Additions
147
+ extend MonkeyBars
148
+
149
+ patch("SomeLibrary", version: "1.0.0", version_check: -> { SomeLibrary::VERSION }) do
150
+ new_class_methods do
151
+ def new_class_method
152
+ "ok"
153
+ end
154
+ end
155
+
156
+ new_constants do
157
+ const_set(:MAX_RETRIES, 5)
158
+ end
159
+ end
160
+ end
161
+ ```
162
+
163
+ ### Use `super_super` to skip the immediate parent
164
+
165
+ ```ruby
166
+ class Parent
167
+ def greet
168
+ "parent"
169
+ end
170
+ end
171
+
172
+ class Child < Parent
173
+ def greet
174
+ "child -> " + super
175
+ end
176
+ end
177
+
178
+ class ChildPatch
179
+ extend MonkeyBars
180
+
181
+ patch(Child, version: "1.0", version_check: -> { "1.0" }) do
182
+ patch_instance_methods(include_super_super: true) do
183
+ def greet
184
+ "patched -> " + super_super
185
+ end
186
+ end
187
+ end
188
+ end
189
+ ```
190
+
191
+ ## Error reference and fixes
192
+
193
+ Use this section when the patch fails. The message usually suggests the fix.
194
+
195
+ - `MonkeyBars::NoPatchableMonkeyFoundError`: the target constant cannot be found.
196
+ Use a valid constant or a callable that returns one.
197
+ - `MonkeyBars::NoPatchableVersionCheckError`: `version_check` is missing or not callable.
198
+ Provide a lambda/proc returning the current version.
199
+ - `MonkeyBars::NoPatchableVersionFoundError`: current version does not match `version`.
200
+ Update the version string or the version check.
201
+ - `MonkeyBars::NoPatchableInstanceMethodFoundError`: method does not exist.
202
+ Move it to `new_instance_methods` or fix the method name.
203
+ - `MonkeyBars::NoPatchableClassMethodFoundError`: method does not exist.
204
+ Move it to `new_class_methods` or fix the method name.
205
+ - `MonkeyBars::MismatchedInstanceMethodArityError`: arity differs.
206
+ Match the signature or set `ignore_arity_errors: true`.
207
+ - `MonkeyBars::MismatchedClassMethodArityError`: arity differs.
208
+ Match the signature or set `ignore_arity_errors: true`.
209
+ - `MonkeyBars::NewInstanceMethodAlreadyExistsError`: method already exists.
210
+ Move it to `patch_instance_methods`.
211
+ - `MonkeyBars::NewClassMethodAlreadyExistsError`: method already exists.
212
+ Move it to `patch_class_methods`.
213
+ - `MonkeyBars::PatchConstantNotFoundError`: constant does not exist.
214
+ Move it to `new_constants` or fix the constant name.
215
+ - `MonkeyBars::NewConstantAlreadyExistsError`: constant already exists.
216
+ Move it to `patch_constants`.
217
+ - `MonkeyBars::PatchAlreadyPerformedError`: `patch!` was called twice.
218
+ Ensure you only call `patch!` once per prepared patch.
219
+
220
+ ## Best practices for LLMs
221
+
222
+ - Always include `version_check` and ensure it returns the exact version string.
223
+ - Prefer `patch(...)` for immediate application unless delayed patching is required.
224
+ - Use `patch_*` helpers for existing methods/constants and `new_*` for new ones.
225
+ - Keep patched method arity identical to the original unless explicitly allowed.
226
+ - Add targeted tests around the patched behavior; avoid testing internal details.
227
+
228
+ ## Testing checklist
229
+
230
+ - Patch applies with the expected version and fails with a mismatched version.
231
+ - Patched method behavior is correct and `super`/`super_super` calls behave as intended.
232
+ - Errors are raised for missing methods/constants and for arity mismatches.
@@ -0,0 +1,75 @@
1
+ # frozen_string_literal: true
2
+
3
+ module MonkeyBars
4
+ class NewInstanceMethodAlreadyExistsError < StandardError
5
+ def initialize(patcher_name, monkey: nil, method: nil)
6
+ super("[#{patcher_name}] The instance method `##{method}` already exists on `#{monkey}` but is marked as new. Perhaps move it to the `patch_instance_methods` block?")
7
+ end
8
+ end
9
+
10
+ class NewClassMethodAlreadyExistsError < StandardError
11
+ def initialize(patcher_name, monkey: nil, method: nil)
12
+ super("[#{patcher_name}] The class method `.#{method}` already exists on `#{monkey}` but is marked as new. Perhaps move it to the `patch_class_methods` block?")
13
+ end
14
+ end
15
+
16
+ class MismatchedInstanceMethodArityError < StandardError
17
+ def initialize(patcher_name, monkey: nil, method: nil, prepatched_arity: nil, patched_arity: nil)
18
+ super("[#{patcher_name}] The instance method `##{method}` on `#{monkey}` has an arity of #{patched_arity} but a prepatched arity of #{prepatched_arity}. If you want to ignore this error, set `ignore_arity_errors: true`.")
19
+ end
20
+ end
21
+
22
+ class MismatchedClassMethodArityError < StandardError
23
+ def initialize(patcher_name, monkey: nil, method: nil, prepatched_arity: nil, patched_arity: nil)
24
+ super("[#{patcher_name}] The class method `.#{method}` on `#{monkey}` has an arity of #{patched_arity} but a prepatched arity of #{prepatched_arity}. If you want to ignore this error, set `ignore_arity_errors: true`.")
25
+ end
26
+ end
27
+
28
+ class NewConstantAlreadyExistsError < StandardError
29
+ def initialize(patcher_name, monkey: nil, constant: nil)
30
+ super("[#{patcher_name}] The constant `#{constant}` already exists on `#{monkey}` but is marked as new. Perhaps move it to the `patch_constants` block?")
31
+ end
32
+ end
33
+
34
+ class NoPatchableMonkeyFoundError < StandardError
35
+ def initialize(patcher_name, monkey: nil)
36
+ super("[#{patcher_name}] Couldn't find `#{monkey}` to patch.")
37
+ end
38
+ end
39
+
40
+ class NoPatchableVersionFoundError < StandardError
41
+ def initialize(patcher_name, monkey: nil, version: nil, current_version: nil)
42
+ super("[#{patcher_name}] Ready to patch `#{monkey}` but found version `#{current_version}` instead of `#{version}`.")
43
+ end
44
+ end
45
+
46
+ class NoPatchableVersionCheckError < StandardError
47
+ def initialize(patcher_name, monkey: nil)
48
+ super("[#{patcher_name}] `version_check` block is missing. Without it, there's no way to know if the version of `#{monkey}` is patchable.")
49
+ end
50
+ end
51
+
52
+ class NoPatchableClassMethodFoundError < StandardError
53
+ def initialize(patcher_name, monkey: nil, method: nil)
54
+ super("[#{patcher_name}] Couldn't find class method `.#{method}` on `#{monkey}` despite it being marked as preexisting. Perhaps move it to the `new_class_methods` block?")
55
+ end
56
+ end
57
+
58
+ class NoPatchableInstanceMethodFoundError < StandardError
59
+ def initialize(patcher_name, monkey: nil, method: nil)
60
+ super("[#{patcher_name}] Couldn't find instance method `##{method}` on `#{monkey}` despite it being marked as patchable. Perhaps move it to the `new_instance_methods` block?")
61
+ end
62
+ end
63
+
64
+ class PatchAlreadyPerformedError < StandardError
65
+ def initialize(patcher_name)
66
+ super("[#{patcher_name}] `#patch!` has already been called and cannot be called again")
67
+ end
68
+ end
69
+
70
+ class PatchConstantNotFoundError < StandardError
71
+ def initialize(patcher_name, monkey: nil, constant: nil)
72
+ super("[#{patcher_name}] Couldn't find constant `#{constant}` on `#{monkey}` despite it being marked as patchable. Perhaps move it to the `new_constants` block?")
73
+ end
74
+ end
75
+ end
@@ -0,0 +1,117 @@
1
+ # frozen_string_literal: true
2
+
3
+ module MonkeyBars
4
+ module Patch
5
+ private
6
+
7
+ def perform_patch
8
+ patch_class_methods_internal
9
+ patch_instance_methods_internal
10
+ patch_constants_internal
11
+ patch_new_constants_internal
12
+
13
+ return unless @post_patch_block.respond_to?(:call)
14
+ if @post_patch_block.arity == 0
15
+ @post_patch_block.call
16
+ else
17
+ @post_patch_block.call(@monkey)
18
+ end
19
+ end
20
+
21
+ def patch_class_methods_internal
22
+ patch_additional_class_methods
23
+ patch_preexisting_class_methods
24
+ end
25
+
26
+ def patch_additional_class_methods
27
+ return unless @new_class_methods_module
28
+ @monkey.extend(@new_class_methods_module)
29
+ end
30
+
31
+ def patch_preexisting_class_methods
32
+ return unless @patch_class_methods_module
33
+ @monkey.singleton_class.prepend(@patch_class_methods_module)
34
+ @monkey.singleton_class.prepend(SuperSuper) if @include_class_super_super
35
+ end
36
+
37
+ def patch_instance_methods_internal
38
+ patch_additional_instance_methods
39
+ patch_preexisting_instance_methods
40
+ end
41
+
42
+ def patch_additional_instance_methods
43
+ return unless @new_instance_methods_module
44
+ @monkey.include(@new_instance_methods_module)
45
+ end
46
+
47
+ def patch_preexisting_instance_methods
48
+ return unless @patch_instance_methods_module
49
+ @monkey.prepend(@patch_instance_methods_module)
50
+ @monkey.include(SuperSuper) if @include_instance_super_super
51
+ end
52
+
53
+ def patch_constants_internal
54
+ return unless @patch_constants_module
55
+ @patch_constants_module.constants(false).each do |const_name|
56
+ new_value = @patch_constants_module.const_get(const_name)
57
+ @monkey.send(:remove_const, const_name)
58
+ @monkey.const_set(const_name, new_value)
59
+ end
60
+ end
61
+
62
+ def patch_new_constants_internal
63
+ return unless @new_constants_module
64
+ @new_constants_module.constants(false).each do |const_name|
65
+ new_value = @new_constants_module.const_get(const_name)
66
+ @monkey.const_set(const_name, new_value)
67
+ end
68
+ end
69
+
70
+ def fetch_const_for(module_or_string_or_block)
71
+ return nil if module_or_string_or_block.nil?
72
+
73
+ return module_or_string_or_block if module_or_string_or_block.is_a?(Module)
74
+
75
+ if module_or_string_or_block.is_a?(String)
76
+ begin
77
+ return Kernel.const_get(module_or_string_or_block)
78
+ rescue NameError
79
+ return nil
80
+ end
81
+ end
82
+
83
+ if module_or_string_or_block.respond_to?(:call)
84
+ begin
85
+ module_or_string_or_block.call
86
+ rescue NameError
87
+ nil
88
+ end
89
+ end
90
+ end
91
+ end
92
+
93
+ module SuperSuper
94
+ def super_super(*args, **kwargs)
95
+ # Get the calling method name from the caller stack
96
+ # Caller format can be: "file.rb:line:in 'method_name'" or "file.rb:line:in `method_name'"
97
+ caller_line = caller(1..1).first
98
+ calling_method_name = caller_line[/in [`'](.*?)[`']/, 1] || caller_line[/in (.*?)$/, 1]
99
+
100
+ raise "Could not determine calling method name from: #{caller_line}" if calling_method_name.nil?
101
+
102
+ if is_a?(Class)
103
+ # For class methods (when extended on a class)
104
+ unless superclass.respond_to?(:singleton_method) && superclass.singleton_methods.include?(calling_method_name.to_sym)
105
+ raise NoMethodError, "undefined method `#{calling_method_name}' for class `#{superclass}'"
106
+ end
107
+ superclass.singleton_method(calling_method_name).call(*args, **kwargs)
108
+ else
109
+ # For instance methods
110
+ unless self.class.superclass&.method_defined?(calling_method_name.to_sym)
111
+ raise(NoMethodError, "undefined method `#{calling_method_name}' for class `#{self.class.superclass}'")
112
+ end
113
+ self.class.superclass.instance_method(calling_method_name).bind_call(self, *args, **kwargs)
114
+ end
115
+ end
116
+ end
117
+ end
@@ -0,0 +1,153 @@
1
+ # frozen_string_literal: true
2
+
3
+ module MonkeyBars
4
+ module Validation
5
+ private
6
+
7
+ def ensure_monkey_exists
8
+ found_const = fetch_const_for(@monkey)
9
+ if found_const
10
+ @monkey = found_const
11
+ else
12
+ raise(NoPatchableMonkeyFoundError.new(@monkey_patcher_name, monkey: @monkey))
13
+ end
14
+ end
15
+
16
+ def ensure_patchable_version
17
+ unless @version_check_block.respond_to?(:call)
18
+ raise(NoPatchableVersionCheckError.new(@monkey_patcher_name, monkey: @monkey))
19
+ end
20
+
21
+ current_version = @version_check_block.call
22
+ if current_version != @version
23
+ raise(NoPatchableVersionFoundError.new(@monkey_patcher_name, monkey: @monkey, version: @version, current_version: current_version))
24
+ end
25
+ end
26
+
27
+ def ensure_patch_instance_methods_are_valid
28
+ return unless @patch_instance_methods.any?
29
+
30
+ @patch_instance_methods_module = Module.new
31
+ @include_instance_super_super = false
32
+ @patch_instance_methods.each do |preexisting_instance_method|
33
+ module_to_prepend = Module.new
34
+ preexisting_instance_method => {block:, ignore_arity_errors:, include_super_super:}
35
+ module_to_prepend.module_eval(&block)
36
+ module_to_prepend.instance_methods.each do |method_name|
37
+ unless @monkey.method_defined?(method_name)
38
+ raise(NoPatchableInstanceMethodFoundError.new(@monkey_patcher_name, monkey: @monkey, method: method_name))
39
+ end
40
+
41
+ next if ignore_arity_errors
42
+
43
+ prepatched_method = @monkey.instance_method(method_name)
44
+ patched_method = module_to_prepend.instance_method(method_name)
45
+ if prepatched_method.arity != patched_method.arity
46
+ raise(MismatchedInstanceMethodArityError.new(@monkey_patcher_name, monkey: @monkey, method: method_name, prepatched_arity: prepatched_method.arity, patched_arity: patched_method.arity))
47
+ end
48
+ end
49
+
50
+ # If anyone asks for super_super, include it
51
+ @include_instance_super_super = true if include_super_super
52
+ @patch_instance_methods_module.module_eval(&block)
53
+ end
54
+ end
55
+
56
+ def ensure_new_instance_methods_are_valid
57
+ return unless @new_instance_methods.any?
58
+
59
+ @new_instance_methods_module = Module.new
60
+ @new_instance_methods.each do |new_instance_methods_block|
61
+ module_to_include = Module.new
62
+ module_to_include.module_eval(&new_instance_methods_block)
63
+ module_to_include.instance_methods.each do |method_name|
64
+ if @monkey.method_defined?(method_name)
65
+ raise(NewInstanceMethodAlreadyExistsError.new(@monkey_patcher_name, monkey: @monkey, method: method_name))
66
+ end
67
+ end
68
+
69
+ @new_instance_methods_module.module_eval(&new_instance_methods_block)
70
+ end
71
+ end
72
+
73
+ def ensure_patch_class_methods_are_valid
74
+ return unless @patch_class_methods.any?
75
+
76
+ @patch_class_methods_module = Module.new
77
+ @include_class_super_super = false
78
+ @patch_class_methods.each do |preexisting_class_method|
79
+ module_to_prepend = Module.new
80
+ preexisting_class_method => {block:, ignore_arity_errors:, include_super_super:}
81
+ module_to_prepend.module_eval(&block)
82
+ module_to_prepend.instance_methods.each do |method_name|
83
+ unless @monkey.singleton_class.method_defined?(method_name)
84
+ raise(NoPatchableClassMethodFoundError.new(@monkey_patcher_name, monkey: @monkey, method: method_name))
85
+ end
86
+
87
+ next if ignore_arity_errors
88
+
89
+ prepatched_method = @monkey.singleton_class.instance_method(method_name)
90
+ patched_method = module_to_prepend.instance_method(method_name)
91
+ if prepatched_method.arity != patched_method.arity
92
+ raise(MismatchedClassMethodArityError.new(@monkey_patcher_name, monkey: @monkey, method: method_name, prepatched_arity: prepatched_method.arity, patched_arity: patched_method.arity))
93
+ end
94
+ end
95
+
96
+ # If anyone asks for super_super, include it
97
+ @include_class_super_super = true if include_super_super
98
+ @patch_class_methods_module.module_eval(&block)
99
+ end
100
+ end
101
+
102
+ def ensure_new_class_methods_are_valid
103
+ return unless @new_class_methods.any?
104
+
105
+ @new_class_methods_module = Module.new
106
+ @new_class_methods.each do |new_class_methods_block|
107
+ module_to_include = Module.new
108
+ module_to_include.module_eval(&new_class_methods_block)
109
+ module_to_include.instance_methods.each do |method_name|
110
+ if @monkey.singleton_class.method_defined?(method_name)
111
+ raise(NewClassMethodAlreadyExistsError.new(@monkey_patcher_name, monkey: @monkey, method: method_name))
112
+ end
113
+ end
114
+
115
+ @new_class_methods_module.module_eval(&new_class_methods_block)
116
+ end
117
+ end
118
+
119
+ def ensure_patch_constants_are_valid
120
+ return unless @patch_constants.any?
121
+
122
+ @patch_constants_module = Module.new
123
+ @patch_constants.each do |redefined_constant|
124
+ module_to_redefine = Module.new
125
+ module_to_redefine.module_eval(&redefined_constant)
126
+ module_to_redefine.constants(false).each do |const_name|
127
+ unless @monkey.constants(false).include?(const_name)
128
+ raise(PatchConstantNotFoundError.new(@monkey_patcher_name, monkey: @monkey, constant: const_name))
129
+ end
130
+ end
131
+
132
+ @patch_constants_module.module_eval(&redefined_constant)
133
+ end
134
+ end
135
+
136
+ def ensure_new_constants_are_valid
137
+ return unless @new_constants.any?
138
+
139
+ @new_constants_module = Module.new
140
+ @new_constants.each do |new_constant|
141
+ module_to_include = Module.new
142
+ module_to_include.module_eval(&new_constant)
143
+ module_to_include.constants(false).each do |const_name|
144
+ if @monkey.constants(false).include?(const_name)
145
+ raise(NewConstantAlreadyExistsError.new(@monkey_patcher_name, monkey: @monkey, constant: const_name))
146
+ end
147
+ end
148
+
149
+ @new_constants_module.module_eval(&new_constant)
150
+ end
151
+ end
152
+ end
153
+ end
@@ -0,0 +1,5 @@
1
+ # frozen_string_literal: true
2
+
3
+ module MonkeyBars
4
+ VERSION = "0.1.0-pre"
5
+ end
@@ -0,0 +1,106 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative "monkey_bars/version"
4
+ require_relative "monkey_bars/errors"
5
+ require_relative "monkey_bars/validation"
6
+ require_relative "monkey_bars/patch"
7
+
8
+ module MonkeyBars
9
+ include Validation
10
+ include Patch
11
+
12
+ def self.extended(monkey_patcher)
13
+ monkey_patcher.instance_variable_set(:@monkey_patcher_name, monkey_patcher.name)
14
+ monkey_patcher.instance_variable_set(:@patch_class_methods, [])
15
+ monkey_patcher.instance_variable_set(:@new_class_methods, [])
16
+ monkey_patcher.instance_variable_set(:@patch_instance_methods, [])
17
+ monkey_patcher.instance_variable_set(:@new_instance_methods, [])
18
+ monkey_patcher.instance_variable_set(:@patch_constants, [])
19
+ monkey_patcher.instance_variable_set(:@new_constants, [])
20
+ end
21
+
22
+ def patch(monkey, version:, version_check:, &block)
23
+ prepare_for_patching(
24
+ monkey,
25
+ version: version,
26
+ version_check: version_check,
27
+ patch_immediately: true,
28
+ &block
29
+ )
30
+ end
31
+ alias_method :🐵, :patch
32
+
33
+ def prepare_for_patching(monkey, version:, version_check:, patch_immediately: false, &block)
34
+ @monkey = monkey
35
+ @version = version
36
+ @version_check_block = version_check
37
+
38
+ yield if block_given?
39
+
40
+ patch! if patch_immediately
41
+ end
42
+
43
+ def patch!
44
+ if @patch_performed
45
+ raise(PatchAlreadyPerformedError.new(@monkey_patcher_name))
46
+ end
47
+
48
+ if @patch_class_methods.empty? &&
49
+ @new_class_methods.empty? &&
50
+ @patch_instance_methods.empty? &&
51
+ @new_instance_methods.empty? &&
52
+ @patch_constants.empty? &&
53
+ @new_constants.empty?
54
+ warn "[#{self}] No methods or constants defined. Maybe you're not calling `#patch!` last?"
55
+ end
56
+
57
+ ensure_monkey_exists
58
+ ensure_patchable_version
59
+ ensure_patch_instance_methods_are_valid
60
+ ensure_new_instance_methods_are_valid
61
+ ensure_patch_class_methods_are_valid
62
+ ensure_new_class_methods_are_valid
63
+ ensure_patch_constants_are_valid
64
+ ensure_new_constants_are_valid
65
+
66
+ perform_patch
67
+
68
+ @patch_performed = true
69
+ end
70
+
71
+ def patch_class_methods(ignore_arity_errors: false, include_super_super: false, &block)
72
+ @patch_class_methods << {
73
+ block: block,
74
+ ignore_arity_errors: ignore_arity_errors,
75
+ include_super_super: include_super_super
76
+ }
77
+ end
78
+
79
+ def new_class_methods(&block)
80
+ @new_class_methods << block
81
+ end
82
+
83
+ def patch_instance_methods(ignore_arity_errors: false, include_super_super: false, &block)
84
+ @patch_instance_methods << {
85
+ block: block,
86
+ ignore_arity_errors: ignore_arity_errors,
87
+ include_super_super: include_super_super
88
+ }
89
+ end
90
+
91
+ def new_instance_methods(&block)
92
+ @new_instance_methods << block
93
+ end
94
+
95
+ def patch_constants(&block)
96
+ @patch_constants << block
97
+ end
98
+
99
+ def new_constants(&block)
100
+ @new_constants << block
101
+ end
102
+
103
+ def post_patch(&block)
104
+ @post_patch_block = block
105
+ end
106
+ end
metadata ADDED
@@ -0,0 +1,106 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: monkey_bars
3
+ version: !ruby/object:Gem::Version
4
+ version: 0.1.0.pre.pre
5
+ platform: ruby
6
+ authors:
7
+ - Andrés Rojas
8
+ autorequire:
9
+ bindir: bin
10
+ cert_chain: []
11
+ date: 2026-02-03 00:00:00.000000000 Z
12
+ dependencies:
13
+ - !ruby/object:Gem::Dependency
14
+ name: rake
15
+ requirement: !ruby/object:Gem::Requirement
16
+ requirements:
17
+ - - "~>"
18
+ - !ruby/object:Gem::Version
19
+ version: '13.0'
20
+ type: :development
21
+ prerelease: false
22
+ version_requirements: !ruby/object:Gem::Requirement
23
+ requirements:
24
+ - - "~>"
25
+ - !ruby/object:Gem::Version
26
+ version: '13.0'
27
+ - !ruby/object:Gem::Dependency
28
+ name: rspec
29
+ requirement: !ruby/object:Gem::Requirement
30
+ requirements:
31
+ - - "~>"
32
+ - !ruby/object:Gem::Version
33
+ version: '3.0'
34
+ type: :development
35
+ prerelease: false
36
+ version_requirements: !ruby/object:Gem::Requirement
37
+ requirements:
38
+ - - "~>"
39
+ - !ruby/object:Gem::Version
40
+ version: '3.0'
41
+ - !ruby/object:Gem::Dependency
42
+ name: standard
43
+ requirement: !ruby/object:Gem::Requirement
44
+ requirements:
45
+ - - "~>"
46
+ - !ruby/object:Gem::Version
47
+ version: '1.40'
48
+ type: :development
49
+ prerelease: false
50
+ version_requirements: !ruby/object:Gem::Requirement
51
+ requirements:
52
+ - - "~>"
53
+ - !ruby/object:Gem::Version
54
+ version: '1.40'
55
+ description: MonkeyBars provides a structured DSL for safely monkey patching Ruby
56
+ modules with built-in version checking, method validation, and constant management
57
+ to prevent silent breakage when dependencies update.
58
+ email:
59
+ - afrojas@gmail.com
60
+ executables: []
61
+ extensions: []
62
+ extra_rdoc_files: []
63
+ files:
64
+ - CODE_OF_CONDUCT.md
65
+ - CONTRIBUTING.md
66
+ - LICENSE.txt
67
+ - README.md
68
+ - docs/llm-usage.md
69
+ - lib/monkey_bars.rb
70
+ - lib/monkey_bars/errors.rb
71
+ - lib/monkey_bars/patch.rb
72
+ - lib/monkey_bars/validation.rb
73
+ - lib/monkey_bars/version.rb
74
+ homepage: https://github.com/afrojas/monkey_bars
75
+ licenses:
76
+ - MIT
77
+ metadata:
78
+ allowed_push_host: https://rubygems.org
79
+ homepage_uri: https://github.com/afrojas/monkey_bars
80
+ source_code_uri: https://github.com/afrojas/monkey_bars
81
+ bug_tracker_uri: https://github.com/afrojas/monkey_bars/issues
82
+ documentation_uri: https://rubydoc.info/gems/monkey_bars
83
+ rubygems_mfa_required: 'true'
84
+ post_install_message:
85
+ rdoc_options: []
86
+ require_paths:
87
+ - lib
88
+ required_ruby_version: !ruby/object:Gem::Requirement
89
+ requirements:
90
+ - - ">="
91
+ - !ruby/object:Gem::Version
92
+ version: 3.2.0
93
+ - - "<"
94
+ - !ruby/object:Gem::Version
95
+ version: 4.1.0
96
+ required_rubygems_version: !ruby/object:Gem::Requirement
97
+ requirements:
98
+ - - ">"
99
+ - !ruby/object:Gem::Version
100
+ version: 1.3.1
101
+ requirements: []
102
+ rubygems_version: 3.4.19
103
+ signing_key:
104
+ specification_version: 4
105
+ summary: Safe, version-aware monkey patching for Ruby modules
106
+ test_files: []