hooki 0.1.0

Sign up to get free protection for your applications and to get access to all the features.
checksums.yaml ADDED
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA256:
3
+ metadata.gz: 462f1c43cafb12860fb320115a484cba35abf5d48b3497ef1d960b87052a94c3
4
+ data.tar.gz: aa84c02c251d5cde835485dfbcef53f7f1ca49a98265fda5ba6c619fab111f25
5
+ SHA512:
6
+ metadata.gz: bd29849dbca0118d9b94b78dc2d000764315eacd60b787a13f4df2caf5beae27ddaf6b81d85047f567a7a4ef528dc013c2b1ed18a2ea0525003e330d2d9f4191
7
+ data.tar.gz: a5d875f67818b50fb3579321d3fb340e517c764325562f9fe422d2c0b585c2577d716b596a8a824b31b7da0d2956520c675f46a24a5aaff9119c0e528f80fe47
data/.rubocop.yml ADDED
@@ -0,0 +1,27 @@
1
+ require:
2
+ - rubocop-minitest
3
+ - rubocop-rake
4
+
5
+ AllCops:
6
+ NewCops: enable
7
+ TargetRubyVersion: 2.6.0
8
+
9
+ Metrics/ClassLength:
10
+ Enabled: false
11
+
12
+ Metrics/MethodLength:
13
+ Enabled: false
14
+
15
+ Style/Documentation:
16
+ Enabled: false
17
+
18
+ Style/StringLiterals:
19
+ Enabled: true
20
+ EnforcedStyle: double_quotes
21
+
22
+ Style/StringLiteralsInInterpolation:
23
+ Enabled: true
24
+ EnforcedStyle: double_quotes
25
+
26
+ Layout/LineLength:
27
+ Max: 120
@@ -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 ceritium@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,15 @@
1
+ # frozen_string_literal: true
2
+
3
+ source "https://rubygems.org"
4
+
5
+ # Specify your gem's dependencies in hooki.gemspec
6
+ gemspec
7
+
8
+ gem "benchmark-ips"
9
+ gem "m"
10
+ gem "minitest", "~> 5.0"
11
+ gem "minitest-focus"
12
+ gem "rake", "~> 13.0"
13
+ gem "rubocop", "~> 1.21"
14
+ gem "rubocop-minitest", require: false
15
+ gem "rubocop-rake", require: false
data/Gemfile.lock ADDED
@@ -0,0 +1,61 @@
1
+ PATH
2
+ remote: .
3
+ specs:
4
+ hooki (0.1.0)
5
+
6
+ GEM
7
+ remote: https://rubygems.org/
8
+ specs:
9
+ ast (2.4.2)
10
+ benchmark-ips (2.12.0)
11
+ json (2.6.3)
12
+ m (1.6.1)
13
+ method_source (>= 0.6.7)
14
+ rake (>= 0.9.2.2)
15
+ method_source (1.0.0)
16
+ minitest (5.17.0)
17
+ minitest-focus (1.3.1)
18
+ minitest (>= 4, < 6)
19
+ parallel (1.22.1)
20
+ parser (3.2.0.0)
21
+ ast (~> 2.4.1)
22
+ rainbow (3.1.1)
23
+ rake (13.0.6)
24
+ regexp_parser (2.7.0)
25
+ rexml (3.2.5)
26
+ rubocop (1.44.1)
27
+ json (~> 2.3)
28
+ parallel (~> 1.10)
29
+ parser (>= 3.2.0.0)
30
+ rainbow (>= 2.2.2, < 4.0)
31
+ regexp_parser (>= 1.8, < 3.0)
32
+ rexml (>= 3.2.5, < 4.0)
33
+ rubocop-ast (>= 1.24.1, < 2.0)
34
+ ruby-progressbar (~> 1.7)
35
+ unicode-display_width (>= 2.4.0, < 3.0)
36
+ rubocop-ast (1.24.1)
37
+ parser (>= 3.1.1.0)
38
+ rubocop-minitest (0.29.0)
39
+ rubocop (>= 1.39, < 2.0)
40
+ rubocop-rake (0.6.0)
41
+ rubocop (~> 1.0)
42
+ ruby-progressbar (1.11.0)
43
+ unicode-display_width (2.4.2)
44
+
45
+ PLATFORMS
46
+ x86_64-darwin-21
47
+ x86_64-linux
48
+
49
+ DEPENDENCIES
50
+ benchmark-ips
51
+ hooki!
52
+ m
53
+ minitest (~> 5.0)
54
+ minitest-focus
55
+ rake (~> 13.0)
56
+ rubocop (~> 1.21)
57
+ rubocop-minitest
58
+ rubocop-rake
59
+
60
+ BUNDLED WITH
61
+ 2.4.7
data/LICENSE.txt ADDED
@@ -0,0 +1,21 @@
1
+ The MIT License (MIT)
2
+
3
+ Copyright (c) 2023 José Galisteo
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,161 @@
1
+ # Hooki
2
+
3
+ Add before and after callbacks to methods.
4
+
5
+ ## Installation
6
+
7
+ Install the gem and add it to the application's Gemfile by executing:
8
+
9
+ $ bundle add hooki
10
+
11
+ If bundler is not being used to manage dependencies, install the gem by executing:
12
+
13
+ $ gem install hooki
14
+
15
+ ## Usage
16
+
17
+ You can use Hooki in several ways to add before and after callbacks to methods.
18
+
19
+ Hooki provides callbacks for instance and singleton methods:
20
+
21
+ instance: `before_method`, `after_method`
22
+ singleton: `before_singleton_method`, `after_singleton_method`
23
+
24
+ All the callbacks accept optional parameters `only` and `except` for filtering
25
+ in which methods trigger the callbacks. `only` and `except` accepts a single symbol or array.
26
+
27
+ This is a basic example:
28
+
29
+ ```ruby
30
+ class Foo
31
+ include Hooki
32
+
33
+ before_method :log_before, only: :bar # or [:bar]
34
+ after_method :log_after, expect: :bar # or [:bar]
35
+
36
+ before_singleton_method :log_singleton_before, only: [:bar] # or :bar
37
+ after_singleton_method :log_singleton_after, expect: [:bar] # or :bar
38
+
39
+ def self.bar
40
+ puts "singleton bar"
41
+ end
42
+
43
+ def self.baz
44
+ puts "singleton baz"
45
+ end
46
+
47
+ def self.log_singleton_before(method_name)
48
+ puts "-- log singleton before #{method_name}"
49
+ end
50
+
51
+ def self.log_singleton_after(method_name)
52
+ puts "-- log singleton after #{method_name}"
53
+ end
54
+
55
+ def bar
56
+ puts "bar"
57
+ end
58
+
59
+ def baz
60
+ puts "baz"
61
+ end
62
+
63
+ private
64
+
65
+ def log_before(method_name)
66
+ puts "-- log before #{method_name}"
67
+ end
68
+
69
+ def log_after(method_name)
70
+ puts "-- log after #{method_name}"
71
+ end
72
+ end
73
+ ```
74
+
75
+ The previous example doesn't seem too useful, Hooki unchains its potential when
76
+ used on class inheritance or modules, for example:
77
+
78
+ ```ruby
79
+ module Logger
80
+ include Hooki
81
+
82
+ before_method :log
83
+
84
+ private
85
+
86
+ def log(method_name)
87
+ puts "running #{method_name}"
88
+ end
89
+ end
90
+
91
+ class Foo
92
+ include Logger
93
+
94
+ def bar
95
+ puts "bar"
96
+ end
97
+
98
+ def baz
99
+ puts "baz"
100
+ end
101
+ end
102
+ ```
103
+
104
+ There are more examples on [`test/examples.rb`](test/examples.rb)
105
+
106
+ ## Performance
107
+
108
+ Good, but how slow is it? Well, this is a lot of metaprograming, so it will be
109
+ slower than the traditional approach.
110
+
111
+ There are two benchmarks in [`benchmarks/`](benchmarks/) folder.
112
+
113
+ The results on my machine are the following:
114
+
115
+ ```
116
+ $ bundle exec ruby benchmarks/no_job.rb
117
+ Warming up --------------------------------------
118
+ with 58.373k i/100ms
119
+ without 377.367k i/100ms
120
+ Calculating -------------------------------------
121
+ with 387.588k (±20.7%) i/s - 1.868M in 5.058400s
122
+ without 3.624M (±19.7%) i/s - 17.359M in 5.025660s
123
+
124
+ Comparison:
125
+ without: 3623753.6 i/s
126
+ with: 387587.8 i/s - 9.35x slower
127
+
128
+
129
+ $ bundle exec ruby benchmarks/with_job.rb
130
+ Warming up --------------------------------------
131
+ with 11.220k i/100ms
132
+ without 14.801k i/100ms
133
+ Calculating -------------------------------------
134
+ with 112.751k (± 8.7%) i/s - 561.000k in 5.025158s
135
+ without 143.033k (±11.0%) i/s - 710.448k in 5.052800s
136
+
137
+ Comparison:
138
+ without: 143033.0 i/s
139
+ with: 112751.4 i/s - 1.27x slower
140
+ ```
141
+
142
+ The "no job" benchmark is ~9 times slower, but it is doing nothing, it doesn't seem
143
+ a realistic scenario. The "with job" benchmark is only a bit slower.
144
+
145
+ ## Development
146
+
147
+ After checking out the repo, run `bin/setup` to install dependencies. Then, run `rake test` to run the tests. You can also run `bin/console` for an interactive prompt that will allow you to experiment.
148
+
149
+ 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).
150
+
151
+ ## Contributing
152
+
153
+ Bug reports and pull requests are welcome on GitHub at https://github.com/ceritium/hooki. 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/ceritium/hooki/blob/master/CODE_OF_CONDUCT.md).
154
+
155
+ ## License
156
+
157
+ The gem is available as open source under the terms of the [MIT License](https://opensource.org/licenses/MIT).
158
+
159
+ ## Code of Conduct
160
+
161
+ Everyone interacting in the Hooki project's codebases, issue trackers, chat rooms and mailing lists is expected to follow the [code of conduct](https://github.com/ceritium/hooki/blob/master/CODE_OF_CONDUCT.md).
data/Rakefile ADDED
@@ -0,0 +1,16 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "bundler/gem_tasks"
4
+ require "rake/testtask"
5
+
6
+ Rake::TestTask.new(:test) do |t|
7
+ t.libs << "test"
8
+ t.libs << "lib"
9
+ t.test_files = FileList["test/**/test_*.rb"]
10
+ end
11
+
12
+ require "rubocop/rake_task"
13
+
14
+ RuboCop::RakeTask.new
15
+
16
+ task default: %i[test rubocop]
@@ -0,0 +1,40 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "benchmark/ips"
4
+ require "hooki"
5
+
6
+ class WithoutHooki
7
+ def bar
8
+ log
9
+ end
10
+
11
+ private
12
+
13
+ def log
14
+ # noop
15
+ end
16
+ end
17
+
18
+ class WithHooki
19
+ prepend Hooki
20
+
21
+ before_method :log
22
+
23
+ def bar
24
+ # noop
25
+ end
26
+
27
+ private
28
+
29
+ def log
30
+ # noop
31
+ end
32
+ end
33
+
34
+ Benchmark.ips do |x|
35
+ x.warmup = 2
36
+ x.time = 5
37
+ x.report("with") { WithHooki.new.bar }
38
+ x.report("without") { WithoutHooki.new.bar }
39
+ x.compare!
40
+ end
@@ -0,0 +1,39 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "benchmark/ips"
4
+ require "hooki"
5
+
6
+ class WithoutHooki
7
+ def bar
8
+ 100.times.reduce(1, :*)
9
+ log
10
+ end
11
+
12
+ private
13
+
14
+ def log; end
15
+ end
16
+
17
+ class WithHooki
18
+ prepend Hooki
19
+
20
+ before_method :log
21
+
22
+ def bar
23
+ 100.times.reduce(1, :*)
24
+ end
25
+
26
+ private
27
+
28
+ def log
29
+ # puts "bar method called"
30
+ end
31
+ end
32
+
33
+ Benchmark.ips do |x|
34
+ x.warmup = 2
35
+ x.time = 5
36
+ x.report("with") { WithHooki.new.bar }
37
+ x.report("without") { WithoutHooki.new.bar }
38
+ x.compare!
39
+ end
data/hooki.gemspec ADDED
@@ -0,0 +1,37 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative "lib/hooki/version"
4
+
5
+ Gem::Specification.new do |spec|
6
+ spec.name = "hooki"
7
+ spec.version = Hooki::VERSION
8
+ spec.authors = ["José Galisteo"]
9
+ spec.email = ["ceritium@gmail.com"]
10
+
11
+ spec.summary = "Add before and after callbacks to methods"
12
+ spec.homepage = "https://github.com/ceritium/hooki"
13
+ spec.license = "MIT"
14
+ spec.required_ruby_version = ">= 2.6.0"
15
+
16
+ spec.metadata["homepage_uri"] = spec.homepage
17
+ spec.metadata["source_code_uri"] = spec.homepage
18
+ # spec.metadata["changelog_uri"] = "TODO: Put your gem's CHANGELOG.md URL here."
19
+
20
+ # Specify which files should be added to the gem when it is released.
21
+ # The `git ls-files -z` loads the files in the RubyGem that have been added into git.
22
+ spec.files = Dir.chdir(__dir__) do
23
+ `git ls-files -z`.split("\x0").reject do |f|
24
+ (File.expand_path(f) == __FILE__) || f.match(%r{\A(?:(?:bin|test|spec|features)/|\.(?:git|circleci)|appveyor)})
25
+ end
26
+ end
27
+ spec.bindir = "exe"
28
+ spec.executables = spec.files.grep(%r{\Aexe/}) { |f| File.basename(f) }
29
+ spec.require_paths = ["lib"]
30
+
31
+ # Uncomment to register a new dependency of your gem
32
+ # spec.add_dependency "example-gem", "~> 1.0"
33
+
34
+ # For more information and examples about making a new gem, check out our
35
+ # guide at: https://bundler.io/guides/creating_gem.html
36
+ spec.metadata["rubygems_mfa_required"] = "true"
37
+ end
data/lib/ext/module.rb ADDED
@@ -0,0 +1,39 @@
1
+ # frozen_string_literal: true
2
+
3
+ class Module
4
+ # Marks the named method as intended to be redefined, if it exists.
5
+ # Suppresses the Ruby method redefinition warning. Prefer
6
+ # #redefine_method where possible.
7
+ def silence_redefinition_of_method(method)
8
+ return unless method_defined?(method) || private_method_defined?(method)
9
+
10
+ # This suppresses the "method redefined" warning; the self-alias
11
+ # looks odd, but means we don't need to generate a unique name
12
+ alias_method method, method
13
+ end
14
+
15
+ # Replaces the existing method definition, if there is one, with the passed
16
+ # block as its body.
17
+ def redefine_method(method, &block)
18
+ visibility = method_visibility(method)
19
+ silence_redefinition_of_method(method)
20
+ define_method(method, &block)
21
+ send(visibility, method)
22
+ end
23
+
24
+ # Replaces the existing singleton method definition, if there is one, with
25
+ # the passed block as its body.
26
+ def redefine_singleton_method(method, &block)
27
+ singleton_class.redefine_method(method, &block)
28
+ end
29
+
30
+ def method_visibility(method) # :nodoc:
31
+ if private_method_defined?(method)
32
+ :private
33
+ elsif protected_method_defined?(method)
34
+ :protected
35
+ else
36
+ :public
37
+ end
38
+ end
39
+ end
@@ -0,0 +1,103 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Hooki
4
+ module ClassMethods
5
+ def before_singleton_method(method_name, only: [], except: [])
6
+ callback = { callback_method_name: method_name, only: wrap(only), except: wrap(except) }
7
+ with_lock do
8
+ @before_singleton_method_callbacks << callback
9
+ @ignore_singleton_methods << method_name
10
+ end
11
+ callback
12
+ end
13
+
14
+ def after_singleton_method(method_name, only: [], except: [])
15
+ callback = { callback_method_name: method_name, only: wrap(only), except: wrap(except) }
16
+ with_lock do
17
+ @after_singleton_method_callbacks << callback
18
+ @ignore_singleton_methods << method_name
19
+ end
20
+ callback
21
+ end
22
+
23
+ def before_method(method_name, only: [], except: [])
24
+ callback = { callback_method_name: method_name, only: wrap(only), except: wrap(except) }
25
+ with_lock do
26
+ @before_method_callbacks << callback
27
+ @ignore_methods << method_name
28
+ end
29
+ callback
30
+ end
31
+
32
+ def after_method(method_name, only: [], except: [])
33
+ callback = { callback_method_name: method_name, only: wrap(only), except: wrap(except) }
34
+ with_lock do
35
+ @after_method_callbacks << callback
36
+ @ignore_methods << method_name
37
+ end
38
+ callback
39
+ end
40
+
41
+ private
42
+
43
+ def singleton_method_added(method_name)
44
+ super
45
+
46
+ return if @ignore_singleton_methods.include?(method_name)
47
+
48
+ before_callbacks = filter_callbacks(@before_singleton_method_callbacks, method_name)
49
+ after_callbacks = filter_callbacks(@after_singleton_method_callbacks, method_name)
50
+
51
+ return if before_callbacks.empty? && after_callbacks.empty?
52
+
53
+ original_method = method(method_name)
54
+
55
+ @ignore_singleton_methods << method_name
56
+ redefine_singleton_method(method_name) do |*args, &blk|
57
+ Hooki::Internal.callbacks(before_callbacks, after_callbacks, self, method_name) do
58
+ original_method.call(*args, &blk)
59
+ end
60
+ end
61
+ end
62
+
63
+ def method_added(method_name)
64
+ super
65
+
66
+ return if @ignore_methods.include?(method_name)
67
+
68
+ before_callbacks = filter_callbacks(@before_method_callbacks, method_name)
69
+ after_callbacks = filter_callbacks(@after_method_callbacks, method_name)
70
+ return if before_callbacks.empty? && after_callbacks.empty?
71
+
72
+ original_method = instance_method(method_name)
73
+
74
+ @ignore_methods << method_name
75
+ redefine_method(method_name) do |*args, &blk|
76
+ Hooki::Internal.callbacks(before_callbacks, after_callbacks, self, method_name) do
77
+ original_method.bind(self).call(*args, &blk)
78
+ end
79
+ end
80
+ end
81
+
82
+ def filter_callbacks(callbacks, method_name)
83
+ callbacks.select do |callback|
84
+ (callback[:only].empty? || callback[:only].include?(method_name)) &&
85
+ (callback[:except].empty? || !callback[:except].include?(method_name))
86
+ end
87
+ end
88
+
89
+ def with_lock(&block)
90
+ @lock.synchronize(&block)
91
+ end
92
+
93
+ def wrap(object)
94
+ if object.nil?
95
+ []
96
+ elsif object.respond_to?(:to_ary)
97
+ object.to_ary || [object]
98
+ else
99
+ [object]
100
+ end
101
+ end
102
+ end
103
+ end
@@ -0,0 +1,31 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Hooki
4
+ module Internal
5
+ class << self
6
+ def callbacks(before_callbacks, after_callbacks, scope, method_name, &blk)
7
+ before_callbacks.each do |callback|
8
+ trigger_callback(callback, scope, method_name)
9
+ end
10
+
11
+ result = blk.call
12
+
13
+ after_callbacks.each do |callback|
14
+ trigger_callback(callback, scope, method_name)
15
+ end
16
+
17
+ result
18
+ end
19
+
20
+ def trigger_callback(callback, scope, method_name)
21
+ method = scope.method(callback[:callback_method_name])
22
+ case method.arity
23
+ when 0
24
+ scope.__send__(callback[:callback_method_name])
25
+ when 1, -1
26
+ scope.__send__(callback[:callback_method_name], method_name)
27
+ end
28
+ end
29
+ end
30
+ end
31
+ end
@@ -0,0 +1,5 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Hooki
4
+ VERSION = "0.1.0"
5
+ end
data/lib/hooki.rb ADDED
@@ -0,0 +1,60 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative "ext/module"
4
+
5
+ require_relative "hooki/version"
6
+ require_relative "hooki/internal"
7
+ require_relative "hooki/class_methods"
8
+
9
+ module Hooki
10
+ def self.prepended(klass)
11
+ hooki(klass)
12
+ end
13
+
14
+ def self.included(klass)
15
+ hooki(klass)
16
+ end
17
+
18
+ INSTANCE_VARIABLE_LIST = %i[
19
+ @before_method_callbacks @before_singleton_method_callbacks
20
+ @after_method_callbacks @after_singleton_method_callbacks
21
+ @ignore_methods @ignore_singleton_methods
22
+ ].freeze
23
+
24
+ def self.hooki(klass)
25
+ klass.extend(Hooki::ClassMethods)
26
+ klass.instance_variable_set(:@lock, Mutex.new)
27
+ INSTANCE_VARIABLE_LIST.each do |instance_variable|
28
+ klass.instance_variable_set(instance_variable, [])
29
+ end
30
+
31
+ klass.instance_variable_set(:@ignore_singleton_methods, %i[included extended])
32
+
33
+ def klass.included(klass)
34
+ super
35
+ Hooki.rehooki(self, klass)
36
+ end
37
+
38
+ def klass.prepended(klass)
39
+ super
40
+ Hooki.rehooki(self, klass)
41
+ end
42
+
43
+ def klass.inherited(klass)
44
+ super
45
+ Hooki.rehooki(self, klass)
46
+ end
47
+
48
+ def klass.append_features(mod)
49
+ super
50
+ mod.include(Hooki) # Notice this
51
+ Hooki.rehooki(self, mod)
52
+ end
53
+ end
54
+
55
+ def self.rehooki(parent, child)
56
+ INSTANCE_VARIABLE_LIST.each do |instance_variable|
57
+ child.instance_variable_set(instance_variable, parent.instance_variable_get(instance_variable))
58
+ end
59
+ end
60
+ end
data/sig/hooki.rbs ADDED
@@ -0,0 +1,4 @@
1
+ module Hooki
2
+ VERSION: String
3
+ # See the writing guide of rbs: https://github.com/ruby/rbs#guides
4
+ end
metadata ADDED
@@ -0,0 +1,62 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: hooki
3
+ version: !ruby/object:Gem::Version
4
+ version: 0.1.0
5
+ platform: ruby
6
+ authors:
7
+ - José Galisteo
8
+ autorequire:
9
+ bindir: exe
10
+ cert_chain: []
11
+ date: 2023-03-31 00:00:00.000000000 Z
12
+ dependencies: []
13
+ description:
14
+ email:
15
+ - ceritium@gmail.com
16
+ executables: []
17
+ extensions: []
18
+ extra_rdoc_files: []
19
+ files:
20
+ - ".rubocop.yml"
21
+ - CODE_OF_CONDUCT.md
22
+ - Gemfile
23
+ - Gemfile.lock
24
+ - LICENSE.txt
25
+ - README.md
26
+ - Rakefile
27
+ - benchmarks/no_job.rb
28
+ - benchmarks/with_job.rb
29
+ - hooki.gemspec
30
+ - lib/ext/module.rb
31
+ - lib/hooki.rb
32
+ - lib/hooki/class_methods.rb
33
+ - lib/hooki/internal.rb
34
+ - lib/hooki/version.rb
35
+ - sig/hooki.rbs
36
+ homepage: https://github.com/ceritium/hooki
37
+ licenses:
38
+ - MIT
39
+ metadata:
40
+ homepage_uri: https://github.com/ceritium/hooki
41
+ source_code_uri: https://github.com/ceritium/hooki
42
+ rubygems_mfa_required: 'true'
43
+ post_install_message:
44
+ rdoc_options: []
45
+ require_paths:
46
+ - lib
47
+ required_ruby_version: !ruby/object:Gem::Requirement
48
+ requirements:
49
+ - - ">="
50
+ - !ruby/object:Gem::Version
51
+ version: 2.6.0
52
+ required_rubygems_version: !ruby/object:Gem::Requirement
53
+ requirements:
54
+ - - ">="
55
+ - !ruby/object:Gem::Version
56
+ version: '0'
57
+ requirements: []
58
+ rubygems_version: 3.0.1
59
+ signing_key:
60
+ specification_version: 4
61
+ summary: Add before and after callbacks to methods
62
+ test_files: []