rubocop-callback_checker 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: 27a8d5e0a0b8d6c92ccabe6a928f106fc80a3d438ed07002686f07bf5c3c07c9
4
+ data.tar.gz: 1bad8a7bb9dcf33f5758655bbdfc208f9849dc75cde2b534dbaedef18e7e31ad
5
+ SHA512:
6
+ metadata.gz: 222120c9a2df85dc84fd57709c17b52b494f9e05b21a9ae64fc7f94d058595f6aebb3a9a821daad78707de021ff796c7039c73710760fd1c410f43e04a07e04f
7
+ data.tar.gz: 29893d82a5f907f2d7cf88781864963e169f6c0e22b1bbc0f5615c0101773aa12f6a53a7e6dc5363c61a6849680090aa4edecd33e3edbe01af3130b47fc63bf6
data/.rspec ADDED
@@ -0,0 +1,3 @@
1
+ --format documentation
2
+ --color
3
+ --require spec_helper
data/.rubocop.yml ADDED
@@ -0,0 +1,15 @@
1
+ require:
2
+ - rubocop-rspec
3
+
4
+ plugins:
5
+ - rubocop-rake
6
+
7
+ AllCops:
8
+ TargetRubyVersion: 3.1
9
+ NewCops: enable
10
+
11
+ Style/StringLiterals:
12
+ EnforcedStyle: double_quotes
13
+
14
+ Style/StringLiteralsInInterpolation:
15
+ EnforcedStyle: double_quotes
data/CHANGELOG.md ADDED
@@ -0,0 +1,5 @@
1
+ ## [Unreleased]
2
+
3
+ ## [0.1.0] - 2025-12-13
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 rahsheen
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,105 @@
1
+ # RuboCop::CallbackChecker
2
+
3
+ A collection of RuboCop cops to ensure your ActiveRecord callbacks are safe, performant, and maintainable.
4
+
5
+ Banning callbacks entirely is a blunt instrument that slows down development. This gem provides a "surgical" approach—allowing callbacks for internal state management while preventing the most common architectural "gotchas" like recursive loops, phantom API calls, and bloated models.
6
+
7
+ ---
8
+
9
+ ## Installation
10
+
11
+ Install the gem and add to the application's Gemfile by executing:
12
+
13
+ ```bash
14
+ bundle add rubocop-callback_checker
15
+
16
+ ```
17
+
18
+ If bundler is not being used to manage dependencies, install the gem by executing:
19
+
20
+ ```bash
21
+ gem install rubocop-callback_checker
22
+
23
+ ```
24
+
25
+ ---
26
+
27
+ ## Usage
28
+
29
+ In your `.rubocop.yml`, add the following:
30
+
31
+ ```yaml
32
+ require:
33
+ - rubocop-callback_checker
34
+
35
+ ```
36
+
37
+ You can then run RuboCop as usual:
38
+
39
+ ```bash
40
+ bundle exec rubocop
41
+
42
+ ```
43
+
44
+ ---
45
+
46
+ ## Cops Included
47
+
48
+ ### 1. `CallbackChecker/NoSideEffectsInCallbacks`
49
+
50
+ **Goal:** Prevent external side effects from running inside a database transaction.
51
+
52
+ If a side effect (like sending an email) triggers in an `after_save` but the transaction later rolls back, the email is sent for data that doesn't exist.
53
+
54
+ * **Bad:** Calling `UserMailer.welcome.deliver_now` in `after_create`.
55
+ * **Good:** Use `after_commit` or `after_create_commit`.
56
+
57
+ ### 2. `CallbackChecker/NoSelfPersistence`
58
+
59
+ **Goal:** Prevent infinite recursion and "Stack Level Too Deep" errors.
60
+
61
+ * **Bad:** Calling `self.save` or `update(status: 'active')` inside a `before_save`.
62
+ * **Good:** Assign attributes directly: `self.status = 'active'`.
63
+
64
+ ### 3. `CallbackChecker/AttributeAssignmentOnly`
65
+
66
+ **Goal:** Reduce unnecessary database I/O.
67
+
68
+ Callbacks that run "before" persistence should only modify the object's memory state, not trigger a secondary database write.
69
+
70
+ * **Bad:** `before_validation { update(attr: 'val') }`
71
+ * **Good:** `before_validation { self.attr = 'val' }`
72
+
73
+ ### 4. `CallbackChecker/CallbackMethodLength`
74
+
75
+ **Goal:** Prevent "Fat Models" and maintain testability.
76
+
77
+ Callbacks should be "post-it notes," not "instruction manuals." If a callback method is too long, it should be moved to a Service Object.
78
+
79
+ * **Default Max:** 10 lines.
80
+
81
+ ### 5. `CallbackChecker/SymbolicConditionals`
82
+
83
+ **Goal:** Improve readability and allow for easier debugging.
84
+
85
+ * **Bad:** `before_save :do_thing, if: -> { status == 'active' && !deleted? }`
86
+ * **Good:** `before_save :do_thing, if: :active_and_present?`
87
+
88
+ ---
89
+
90
+ ## Development
91
+
92
+ After checking out the repo, run `bin/setup` to install dependencies. Then, run `rake spec` to run the tests.
93
+
94
+ 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`.
95
+
96
+ ## Contributing
97
+
98
+ Bug reports and pull requests are welcome on GitHub at [https://github.com/](https://github.com/)[USERNAME]/rubocop-callback_checker.
99
+
100
+ ## License
101
+
102
+ The gem is available as open source under the terms of the [MIT License](https://opensource.org/licenses/MIT).
103
+
104
+ ---
105
+
data/Rakefile ADDED
@@ -0,0 +1,12 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "bundler/gem_tasks"
4
+ require "rspec/core/rake_task"
5
+
6
+ RSpec::Core::RakeTask.new(:spec)
7
+
8
+ require "rubocop/rake_task"
9
+
10
+ RuboCop::RakeTask.new
11
+
12
+ task default: %i[spec rubocop]
@@ -0,0 +1,30 @@
1
+ CallbackChecker:
2
+ Exclude:
3
+ - 'db/**/*'
4
+ - 'config/**/*'
5
+
6
+ CallbackChecker/NoSideEffectsInCallbacks:
7
+ Description: 'Disallows logic with side effects (like external APIs or mailers) in before_* and after_save callbacks.'
8
+ Enabled: true
9
+ Severity: warning
10
+
11
+ CallbackChecker/AvoidSelfPersistence:
12
+ Description: 'Avoid calling persistence methods on self within callbacks to prevent infinite loops.'
13
+ Enabled: true
14
+ Severity: warning
15
+
16
+ CallbackChecker/AttributeAssignmentOnly:
17
+ Description: 'Use attribute assignment instead of persistence methods in before_* callbacks.'
18
+ Enabled: true
19
+ Severity: warning
20
+
21
+ CallbackChecker/CallbackMethodLength:
22
+ Description: 'Callback methods should be short. Complex logic belongs in service objects.'
23
+ Enabled: true
24
+ Severity: warning
25
+ Max: 5
26
+
27
+ CallbackChecker/ConditionalStyle:
28
+ Description: 'Use named methods instead of procs/strings for callback conditionals.'
29
+ Enabled: true
30
+ Severity: warning
@@ -0,0 +1,6 @@
1
+ #!/usr/bin/env ruby
2
+ # frozen_string_literal: true
3
+
4
+ require_relative '../lib/callback_checker/cli'
5
+
6
+ exit CallbackChecker::CLI.run(ARGV)
@@ -0,0 +1,104 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative 'prism_analyzer'
4
+ require_relative '../rubocop/callback_checker/version'
5
+ require 'optparse'
6
+
7
+ module CallbackChecker
8
+ VERSION = Rubocop::CallbackChecker::VERSION
9
+
10
+ class CLI
11
+ def self.run(argv)
12
+ new(argv).run
13
+ end
14
+
15
+ def initialize(argv)
16
+ @argv = argv
17
+ @paths = []
18
+ @options = {}
19
+ end
20
+
21
+ def run
22
+ parse_options
23
+
24
+ if @paths.empty?
25
+ puts "Usage: rubocop-callback-checker [options] FILE..."
26
+ puts "Try 'rubocop-callback-checker --help' for more information."
27
+ return 1
28
+ end
29
+
30
+ files = collect_files(@paths)
31
+
32
+ if files.empty?
33
+ puts "No Ruby files found to analyze."
34
+ return 1
35
+ end
36
+
37
+ total_offenses = 0
38
+
39
+ files.each do |file|
40
+ offenses = PrismAnalyzer.analyze_file(file)
41
+
42
+ if offenses.any?
43
+ total_offenses += offenses.size
44
+ print_offenses(file, offenses)
45
+ end
46
+ end
47
+
48
+ print_summary(files.size, total_offenses)
49
+
50
+ total_offenses > 0 ? 1 : 0
51
+ end
52
+
53
+ private
54
+
55
+ def parse_options
56
+ OptionParser.new do |opts|
57
+ opts.banner = "Usage: rubocop-callback-checker [options] FILE..."
58
+
59
+ opts.on("-h", "--help", "Print this help") do
60
+ puts opts
61
+ exit 0
62
+ end
63
+
64
+ opts.on("-v", "--version", "Print version") do
65
+ puts "rubocop-callback-checker version #{VERSION}"
66
+ exit 0
67
+ end
68
+ end.parse!(@argv)
69
+
70
+ @paths = @argv
71
+ end
72
+
73
+ def collect_files(paths)
74
+ files = []
75
+
76
+ paths.each do |path|
77
+ if File.file?(path)
78
+ files << path if path.end_with?('.rb')
79
+ elsif File.directory?(path)
80
+ files.concat(Dir.glob(File.join(path, '**', '*.rb')))
81
+ else
82
+ warn "Warning: #{path} is not a file or directory"
83
+ end
84
+ end
85
+
86
+ files
87
+ end
88
+
89
+ def print_offenses(file, offenses)
90
+ puts "\n#{file}"
91
+
92
+ offenses.each do |offense|
93
+ location = offense[:location]
94
+ puts " #{location[:start_line]}:#{location[:start_column]}: #{offense[:message]}"
95
+ puts " #{offense[:code]}"
96
+ end
97
+ end
98
+
99
+ def print_summary(file_count, offense_count)
100
+ puts "\n" + "=" * 80
101
+ puts "#{file_count} file(s) inspected, #{offense_count} offense(s) detected"
102
+ end
103
+ end
104
+ end