interactor-validation 0.1.1

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: 8a2389fc324f275ef082e2d5b24174f8c753c88a5adc3d4ed6499670b6a1da11
4
+ data.tar.gz: dc45f25929ca97a2a49dc4663e885dff8780d1dc54d4d11bb8555e39fd00c11f
5
+ SHA512:
6
+ metadata.gz: dfc83bceb6887d5b45338a0801ba61e9e978bbbd319fa5b43d754bc50cc18f863fda7d841e1dd8a749292bc9ffb998bb476df57b0e76091075723fc157281d2f
7
+ data.tar.gz: f0ab78c0e9f364da7c343fd5799d020c8dd4e3139c7b859c95ae8f7d10470c24a6b1e519516b27b0eff06627549075bb8b1d1e125afde15f2cea2b88e91459d3
data/CHANGELOG.md ADDED
@@ -0,0 +1,5 @@
1
+ ## [Unreleased]
2
+
3
+ ## [0.1.0] - 2025-11-16
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 Wilson Anciro
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,241 @@
1
+ # Interactor::Validation
2
+
3
+ Add Rails-style parameter validation to your [Interactor](https://github.com/collectiveidea/interactor) service objects with simple, declarative syntax.
4
+
5
+ ## Installation
6
+
7
+ ```ruby
8
+ gem "interactor-validation"
9
+ ```
10
+
11
+ ## Quick Start
12
+
13
+ ```ruby
14
+ class CreateUser
15
+ include Interactor
16
+ include Interactor::Validation
17
+
18
+ params :email, :username, :age
19
+
20
+ validates :email, presence: true, format: { with: URI::MailTo::EMAIL_REGEXP }
21
+ validates :username, presence: true, length: { minimum: 3, maximum: 20 }
22
+ validates :age, numericality: { greater_than: 0, less_than: 150 }
23
+
24
+ def call
25
+ user = User.create!(email: email, username: username, age: age)
26
+ context.user = user
27
+ end
28
+ end
29
+
30
+ # Success
31
+ result = CreateUser.call(email: "dev@example.com", username: "developer", age: 25)
32
+ result.success? # => true
33
+ result.user # => #<User...>
34
+
35
+ # Failure - automatic validation
36
+ result = CreateUser.call(email: "", username: "ab", age: -5)
37
+ result.failure? # => true
38
+ result.errors # => [
39
+ # { code: "EMAIL_IS_REQUIRED" },
40
+ # { code: "USERNAME_BELOW_MIN_LENGTH_3" },
41
+ # { code: "AGE_MUST_BE_GREATER_THAN_0" }
42
+ # ]
43
+ ```
44
+
45
+ ## Features
46
+
47
+ ### Parameter Declaration
48
+
49
+ Use `params` to declare expected parameters - they're automatically delegated to context:
50
+
51
+ ```ruby
52
+ params :user_id, :action
53
+
54
+ def call
55
+ # Access directly instead of context.user_id
56
+ user = User.find(user_id)
57
+ user.perform(action)
58
+ end
59
+ ```
60
+
61
+ ### Validation Rules
62
+
63
+ All validations run **before** your `call` method. If validation fails, the interactor stops and returns structured errors.
64
+
65
+ **Presence**
66
+ ```ruby
67
+ validates :name, presence: true
68
+ # Error: { code: "NAME_IS_REQUIRED" }
69
+ ```
70
+
71
+ **Format (Regex)**
72
+ ```ruby
73
+ validates :email, format: { with: /\A[\w+\-.]+@[a-z\d\-]+(\.[a-z\d\-]+)*\.[a-z]+\z/i }
74
+ # Error: { code: "EMAIL_INVALID_FORMAT" }
75
+ ```
76
+
77
+ **Length**
78
+ ```ruby
79
+ validates :password, length: { minimum: 8, maximum: 128 }
80
+ validates :code, length: { is: 6 }
81
+ # Errors: { code: "PASSWORD_BELOW_MIN_LENGTH_8" }
82
+ # { code: "CODE_INVALID_LENGTH_6" }
83
+ ```
84
+
85
+ **Inclusion**
86
+ ```ruby
87
+ validates :status, inclusion: { in: %w[active pending inactive] }
88
+ # Error: { code: "STATUS_NOT_IN_LIST" }
89
+ ```
90
+
91
+ **Numericality**
92
+ ```ruby
93
+ validates :price, numericality: { greater_than_or_equal_to: 0 }
94
+ validates :quantity, numericality: { greater_than: 0, less_than_or_equal_to: 100 }
95
+ # Errors: { code: "PRICE_MUST_BE_GREATER_THAN_OR_EQUAL_TO_0" }
96
+ ```
97
+
98
+ ### Error Formats
99
+
100
+ The gem supports two error formatting modes:
101
+
102
+ #### Code Mode (Default)
103
+
104
+ Returns structured error codes ideal for APIs and i18n:
105
+
106
+ ```ruby
107
+ result.errors # => [
108
+ # { code: "EMAIL_IS_REQUIRED" },
109
+ # { code: "USERNAME_BELOW_MIN_LENGTH_3" }
110
+ # ]
111
+ ```
112
+
113
+ #### Default Mode
114
+
115
+ Returns ActiveModel-style errors with human-readable messages:
116
+
117
+ ```ruby
118
+ Interactor::Validation.configure do |config|
119
+ config.error_mode = :default
120
+ end
121
+
122
+ result.errors # => [
123
+ # { attribute: :email, type: :blank, message: "Email can't be blank" },
124
+ # { attribute: :username, type: :too_short, message: "Username is too short (minimum is 3 characters)" }
125
+ # ]
126
+ ```
127
+
128
+ ## Configuration
129
+
130
+ ### Global Configuration
131
+
132
+ Configure validation behavior for all interactors:
133
+
134
+ ```ruby
135
+ # config/initializers/interactor_validation.rb
136
+ Interactor::Validation.configure do |config|
137
+ # Error format mode: :code (default) or :default
138
+ config.error_mode = :code
139
+
140
+ # Stop validation at first error (default: false)
141
+ config.halt_on_first_error = false
142
+ end
143
+ ```
144
+
145
+ ### Per-Interactor Configuration
146
+
147
+ Override global settings for specific interactors:
148
+
149
+ ```ruby
150
+ class CreateUser
151
+ include Interactor
152
+ include Interactor::Validation
153
+
154
+ configure_validation do |config|
155
+ config.error_mode = :default
156
+ config.halt_on_first_error = true
157
+ end
158
+
159
+ validates :username, presence: true
160
+ validates :email, presence: true
161
+ end
162
+ ```
163
+
164
+ ### Custom Error Messages
165
+
166
+ Provide custom error messages for any validation:
167
+
168
+ ```ruby
169
+ # With :code mode
170
+ configure_validation do |config|
171
+ config.error_mode = :code
172
+ end
173
+
174
+ validates :username, presence: { message: "CUSTOM_REQUIRED_ERROR" }
175
+ validates :email, format: { with: /@/, message: "CUSTOM_FORMAT_ERROR" }
176
+ # => { code: "USERNAME_CUSTOM_REQUIRED_ERROR" }
177
+ # => { code: "EMAIL_CUSTOM_FORMAT_ERROR" }
178
+
179
+ # With :default mode
180
+ configure_validation do |config|
181
+ config.error_mode = :default
182
+ end
183
+
184
+ validates :bio, length: { maximum: 500, message: "is too long (max 500 chars)" }
185
+ # => { attribute: :bio, type: :too_long, message: "is too long (max 500 chars)" }
186
+ ```
187
+
188
+ ### Advanced Usage
189
+
190
+ #### Halt on First Error
191
+
192
+ Improve performance by stopping validation at the first failure:
193
+
194
+ ```ruby
195
+ configure_validation do |config|
196
+ config.halt_on_first_error = true # Stop at first error
197
+ end
198
+
199
+ validates :field1, presence: true
200
+ validates :field2, presence: true # Won't run if field1 fails
201
+ validates :field3, presence: true # Won't run if field1 or field2 fails
202
+ ```
203
+
204
+ #### Integration with ActiveModel Validations
205
+
206
+ Use ActiveModel's custom validation callbacks:
207
+
208
+ ```ruby
209
+ class CreateUser
210
+ include Interactor
211
+ include Interactor::Validation
212
+
213
+ params :user_data
214
+
215
+ validate :check_user_data_structure
216
+ validates :username, presence: true
217
+
218
+ def check_user_data_structure
219
+ errors.add(:user_data, "must be a Hash") unless user_data.is_a?(Hash)
220
+ end
221
+ end
222
+ ```
223
+
224
+ ## Development
225
+
226
+ ```bash
227
+ bin/setup # Install dependencies
228
+ bundle exec rspec # Run tests
229
+ bundle exec rubocop # Lint code
230
+ bin/console # Interactive console
231
+ ```
232
+
233
+ ## Requirements
234
+
235
+ - Ruby >= 3.2.0
236
+ - Interactor ~> 3.0
237
+ - ActiveModel >= 6.0
238
+
239
+ ## License
240
+
241
+ MIT License - see [LICENSE.txt](LICENSE.txt)
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,41 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Interactor
4
+ module Validation
5
+ # Configuration class for interactor validation behavior
6
+ class Configuration
7
+ attr_accessor :halt_on_first_error
8
+ attr_reader :error_mode
9
+
10
+ # Available error modes:
11
+ # - :default - Uses ActiveModel-style human-readable messages
12
+ # - :code - Returns structured error codes (e.g., USERNAME_IS_REQUIRED) [DEFAULT]
13
+ def initialize
14
+ @error_mode = :code
15
+ @halt_on_first_error = false
16
+ end
17
+
18
+ def error_mode=(mode)
19
+ raise ArgumentError, "Invalid error_mode: #{mode}. Must be :default or :code" unless %i[default code].include?(mode)
20
+
21
+ @error_mode = mode
22
+ end
23
+ end
24
+
25
+ class << self
26
+ attr_writer :configuration
27
+
28
+ def configuration
29
+ @configuration ||= Configuration.new
30
+ end
31
+
32
+ def configure
33
+ yield(configuration)
34
+ end
35
+
36
+ def reset_configuration!
37
+ @configuration = Configuration.new
38
+ end
39
+ end
40
+ end
41
+ end
@@ -0,0 +1,32 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Interactor
4
+ module Validation
5
+ module Params
6
+ extend ActiveSupport::Concern
7
+
8
+ included do
9
+ class_attribute :_declared_params, instance_writer: false, default: []
10
+ end
11
+
12
+ class_methods do
13
+ # Declares parameters that will be delegated from context
14
+ # and registered for validation
15
+ #
16
+ # @param param_names [Array<Symbol>] the parameter names to declare
17
+ # @example
18
+ # params :username, :password
19
+ def params(*param_names)
20
+ param_names.each do |param_name|
21
+ # Ensure we're working with a copy to avoid modifying parent's array
22
+ current_params = _declared_params.dup
23
+ self._declared_params = current_params + [param_name] unless current_params.include?(param_name)
24
+
25
+ # Delegate to context for easy access
26
+ delegate param_name, to: :context
27
+ end
28
+ end
29
+ end
30
+ end
31
+ end
32
+ end
@@ -0,0 +1,311 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Interactor
4
+ module Validation
5
+ module Validates
6
+ extend ActiveSupport::Concern
7
+
8
+ included do
9
+ class_attribute :_param_validations, instance_writer: false, default: {}
10
+ end
11
+
12
+ def self.included(base)
13
+ super
14
+ # Include ActiveModel::Validations first, then prepend our override
15
+ base.include ActiveModel::Validations unless base.included_modules.include?(ActiveModel::Validations)
16
+ base.singleton_class.prepend(ClassMethodsOverride)
17
+ end
18
+
19
+ module ClassMethodsOverride
20
+ # Override ActiveModel's validates to handle our simple validation rules
21
+ # Falls back to ActiveModel's validates for complex cases
22
+ def validates(param_name, **rules)
23
+ # If no keyword arguments, delegate to ActiveModel's validates
24
+ return super(param_name) if rules.empty?
25
+
26
+ # Merge validation rules for the same param, ensuring we don't modify parent's hash
27
+ current_validations = _param_validations.dup
28
+ existing_rules = current_validations[param_name] || {}
29
+ self._param_validations = current_validations.merge(param_name => existing_rules.merge(rules))
30
+ end
31
+ end
32
+
33
+ private
34
+
35
+ # Validates all declared parameters before execution
36
+ def validate_params!
37
+ # Trigger ActiveModel validations first (validate callbacks)
38
+ # This runs any custom validations defined with validate :method_name
39
+ # NOTE: valid? must be called BEFORE adding our custom errors
40
+ # because it clears the errors object
41
+ valid?
42
+
43
+ # Run our custom param validations after ActiveModel validations
44
+ self.class._param_validations.each do |param_name, rules|
45
+ # Safe param access - returns nil if not present in context
46
+ value = context.respond_to?(param_name) ? context.public_send(param_name) : nil
47
+ validate_param(param_name, value, rules)
48
+
49
+ # Halt on first error if configured
50
+ break if current_config.halt_on_first_error && errors.any?
51
+ end
52
+
53
+ return if errors.empty?
54
+
55
+ context.fail!(errors: formatted_errors)
56
+ end
57
+
58
+ # Get the current configuration (instance config overrides global config)
59
+ def current_config
60
+ self.class.validation_config || Interactor::Validation.configuration
61
+ end
62
+
63
+ # Validates a single parameter with the given rules
64
+ def validate_param(param_name, value, rules)
65
+ validate_presence(param_name, value, rules)
66
+ validate_format(param_name, value, rules)
67
+ validate_length(param_name, value, rules)
68
+ validate_inclusion(param_name, value, rules)
69
+ validate_numericality(param_name, value, rules)
70
+ end
71
+
72
+ def validate_presence(param_name, value, rules)
73
+ return unless rules[:presence]
74
+ return if value.present?
75
+
76
+ message = extract_message(rules[:presence], :blank)
77
+ add_error(param_name, message, :blank)
78
+ end
79
+
80
+ def validate_format(param_name, value, rules)
81
+ return unless rules[:format] && value.present?
82
+
83
+ format_options = rules[:format]
84
+ pattern = format_options.is_a?(Hash) ? format_options[:with] : format_options
85
+ return if value.to_s.match?(pattern)
86
+
87
+ message = extract_message(format_options, :invalid)
88
+ add_error(param_name, message, :invalid)
89
+ end
90
+
91
+ def validate_length(param_name, value, rules)
92
+ return unless rules[:length] && value.present?
93
+
94
+ length_rules = rules[:length]
95
+ length = value.to_s.length
96
+
97
+ if length_rules[:maximum] && length > length_rules[:maximum]
98
+ message = extract_message(length_rules, :too_long, count: length_rules[:maximum])
99
+ add_error(param_name, message, :too_long, count: length_rules[:maximum])
100
+ end
101
+
102
+ if length_rules[:minimum] && length < length_rules[:minimum]
103
+ message = extract_message(length_rules, :too_short, count: length_rules[:minimum])
104
+ add_error(param_name, message, :too_short, count: length_rules[:minimum])
105
+ end
106
+
107
+ return unless length_rules[:is] && length != length_rules[:is]
108
+
109
+ message = extract_message(length_rules, :wrong_length, count: length_rules[:is])
110
+ add_error(param_name, message, :wrong_length, count: length_rules[:is])
111
+ end
112
+
113
+ def validate_inclusion(param_name, value, rules)
114
+ return unless rules[:inclusion] && value.present?
115
+
116
+ inclusion_options = rules[:inclusion]
117
+ allowed_values = inclusion_options.is_a?(Hash) ? inclusion_options[:in] : inclusion_options
118
+ return if allowed_values.include?(value)
119
+
120
+ message = extract_message(inclusion_options, :inclusion)
121
+ add_error(param_name, message, :inclusion)
122
+ end
123
+
124
+ def validate_numericality(param_name, value, rules)
125
+ return unless rules[:numericality] && value.present?
126
+
127
+ numeric_rules = rules[:numericality].is_a?(Hash) ? rules[:numericality] : {}
128
+
129
+ unless numeric?(value)
130
+ message = extract_message(numeric_rules, :not_a_number)
131
+ add_error(param_name, message, :not_a_number)
132
+ return
133
+ end
134
+
135
+ numeric_value = coerce_to_numeric(value)
136
+ validate_numeric_constraints(param_name, numeric_value, numeric_rules)
137
+ end
138
+
139
+ def numeric?(value)
140
+ value.is_a?(Numeric) || value.to_s.match?(/\A-?\d+(\.\d+)?\z/)
141
+ end
142
+
143
+ def coerce_to_numeric(value)
144
+ value.is_a?(Numeric) ? value : value.to_s.to_f
145
+ end
146
+
147
+ def validate_numeric_constraints(param_name, value, rules)
148
+ if rules[:greater_than] && value <= rules[:greater_than]
149
+ message = extract_message(rules, :greater_than, count: rules[:greater_than])
150
+ add_error(param_name, message, :greater_than, count: rules[:greater_than])
151
+ end
152
+
153
+ if rules[:greater_than_or_equal_to] && value < rules[:greater_than_or_equal_to]
154
+ message = extract_message(rules, :greater_than_or_equal_to, count: rules[:greater_than_or_equal_to])
155
+ add_error(param_name, message, :greater_than_or_equal_to, count: rules[:greater_than_or_equal_to])
156
+ end
157
+
158
+ if rules[:less_than] && value >= rules[:less_than]
159
+ message = extract_message(rules, :less_than, count: rules[:less_than])
160
+ add_error(param_name, message, :less_than, count: rules[:less_than])
161
+ end
162
+
163
+ if rules[:less_than_or_equal_to] && value > rules[:less_than_or_equal_to]
164
+ message = extract_message(rules, :less_than_or_equal_to, count: rules[:less_than_or_equal_to])
165
+ add_error(param_name, message, :less_than_or_equal_to, count: rules[:less_than_or_equal_to])
166
+ end
167
+
168
+ return unless rules[:equal_to] && value != rules[:equal_to]
169
+
170
+ message = extract_message(rules, :equal_to, count: rules[:equal_to])
171
+ add_error(param_name, message, :equal_to, count: rules[:equal_to])
172
+ end
173
+
174
+ # Extract custom message from validation options
175
+ # @param options [Hash, Boolean] validation options
176
+ # @param error_type [Symbol] the type of error
177
+ # @param interpolations [Hash] values to interpolate into message
178
+ # @return [String, nil] custom message if provided
179
+ def extract_message(options, _error_type, **_interpolations)
180
+ return nil unless options.is_a?(Hash)
181
+
182
+ options[:message]
183
+ end
184
+
185
+ # Add an error with proper formatting based on error mode
186
+ # @param param_name [Symbol] the parameter name
187
+ # @param custom_message [String, nil] custom error message if provided
188
+ # @param error_type [Symbol] the type of validation error
189
+ # @param interpolations [Hash] values to interpolate into the message
190
+ def add_error(param_name, custom_message, error_type, **interpolations)
191
+ if current_config.error_mode == :code
192
+ # Code mode: use custom message or generate code
193
+ code_message = custom_message || error_code_for(error_type, **interpolations)
194
+ errors.add(param_name, code_message)
195
+ elsif custom_message
196
+ # Default mode: use ActiveModel's error messages
197
+ errors.add(param_name, custom_message)
198
+ else
199
+ errors.add(param_name, error_type, **interpolations)
200
+ end
201
+ end
202
+
203
+ # Generate error code for :code mode
204
+ # @param error_type [Symbol] the type of validation error
205
+ # @param interpolations [Hash] values to interpolate into the code
206
+ # @return [String] the error code
207
+ def error_code_for(error_type, **interpolations)
208
+ case error_type
209
+ when :blank
210
+ "IS_REQUIRED"
211
+ when :invalid
212
+ "INVALID_FORMAT"
213
+ when :too_long
214
+ "EXCEEDS_MAX_LENGTH_#{interpolations[:count]}"
215
+ when :too_short
216
+ "BELOW_MIN_LENGTH_#{interpolations[:count]}"
217
+ when :wrong_length
218
+ "MUST_BE_LENGTH_#{interpolations[:count]}"
219
+ when :inclusion
220
+ "NOT_IN_ALLOWED_VALUES"
221
+ when :not_a_number
222
+ "MUST_BE_A_NUMBER"
223
+ when :greater_than
224
+ "MUST_BE_GREATER_THAN_#{interpolations[:count]}"
225
+ when :greater_than_or_equal_to
226
+ "MUST_BE_AT_LEAST_#{interpolations[:count]}"
227
+ when :less_than
228
+ "MUST_BE_LESS_THAN_#{interpolations[:count]}"
229
+ when :less_than_or_equal_to
230
+ "MUST_BE_AT_MOST_#{interpolations[:count]}"
231
+ when :equal_to
232
+ "MUST_BE_EQUAL_TO_#{interpolations[:count]}"
233
+ else
234
+ error_type.to_s.upcase
235
+ end
236
+ end
237
+
238
+ # Formats errors into the expected structure
239
+ def formatted_errors
240
+ if current_config.error_mode == :code
241
+ # Code mode: return structured error codes
242
+ errors.map do |error|
243
+ param_name = error.attribute.to_s.upcase
244
+ message = error.message
245
+
246
+ { code: "#{param_name}_#{message}" }
247
+ end
248
+ else
249
+ # Default mode: return ActiveModel-style errors
250
+ errors.map do |error|
251
+ # Build a human-readable message manually to avoid anonymous class issues
252
+ message = build_error_message(error)
253
+ {
254
+ attribute: error.attribute,
255
+ type: error.type,
256
+ message: message
257
+ }
258
+ end
259
+ end
260
+ end
261
+
262
+ # Build a human-readable error message
263
+ # @param error [ActiveModel::Error] the error object
264
+ # @return [String] the formatted message
265
+ def build_error_message(error)
266
+ # Try to use ActiveModel's message first
267
+ error.message if error.respond_to?(:message)
268
+ rescue ArgumentError
269
+ # Fallback for anonymous classes or other issues
270
+ attribute_name = error.attribute.to_s.humanize
271
+ error_message = error.options[:message] || default_message_for_type(error.type, error.options)
272
+ "#{attribute_name} #{error_message}"
273
+ end
274
+
275
+ # Get default message for error type
276
+ # @param type [Symbol] the error type
277
+ # @param options [Hash] error options with interpolations
278
+ # @return [String] the default message
279
+ def default_message_for_type(type, options = {})
280
+ case type
281
+ when :blank
282
+ "can't be blank"
283
+ when :invalid
284
+ "is invalid"
285
+ when :too_long
286
+ "is too long (maximum is #{options[:count]} characters)"
287
+ when :too_short
288
+ "is too short (minimum is #{options[:count]} characters)"
289
+ when :wrong_length
290
+ "is the wrong length (should be #{options[:count]} characters)"
291
+ when :inclusion
292
+ "is not included in the list"
293
+ when :not_a_number
294
+ "is not a number"
295
+ when :greater_than
296
+ "must be greater than #{options[:count]}"
297
+ when :greater_than_or_equal_to
298
+ "must be greater than or equal to #{options[:count]}"
299
+ when :less_than
300
+ "must be less than #{options[:count]}"
301
+ when :less_than_or_equal_to
302
+ "must be less than or equal to #{options[:count]}"
303
+ when :equal_to
304
+ "must be equal to #{options[:count]}"
305
+ else
306
+ "is invalid"
307
+ end
308
+ end
309
+ end
310
+ end
311
+ end
@@ -0,0 +1,7 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Interactor
4
+ module Validation
5
+ VERSION = "0.1.1"
6
+ end
7
+ end
@@ -0,0 +1,53 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "interactor"
4
+ require "active_support/concern"
5
+ require "active_model"
6
+
7
+ require_relative "validation/version"
8
+ require_relative "validation/configuration"
9
+ require_relative "validation/params"
10
+ require_relative "validation/validates"
11
+
12
+ module Interactor
13
+ module Validation
14
+ class Error < StandardError; end
15
+
16
+ extend ActiveSupport::Concern
17
+
18
+ included do
19
+ include Params
20
+ include Validates
21
+
22
+ # Instance-level configuration (can override global config)
23
+ class_attribute :validation_config, instance_writer: false, default: nil
24
+ end
25
+
26
+ class_methods do
27
+ # Configure validation behavior for this interactor class
28
+ # @example
29
+ # configure_validation do |config|
30
+ # config.error_mode = :code
31
+ # end
32
+ def configure_validation
33
+ self.validation_config ||= Configuration.new
34
+ yield(validation_config)
35
+ end
36
+ end
37
+
38
+ def self.included(base)
39
+ super
40
+ # Set up the validation hook after all modules are included
41
+ # Use class_eval to ensure we're in the right context
42
+ base.class_eval do
43
+ before :validate_params! if respond_to?(:before)
44
+
45
+ # Set up inherited hook to ensure child classes also get the before hook
46
+ def self.inherited(subclass)
47
+ super
48
+ subclass.before :validate_params! if subclass.respond_to?(:before)
49
+ end
50
+ end
51
+ end
52
+ end
53
+ end
@@ -0,0 +1,6 @@
1
+ module Interactor
2
+ module Validation
3
+ VERSION: String
4
+ # See the writing guide of rbs: https://github.com/ruby/rbs#guides
5
+ end
6
+ end
metadata ADDED
@@ -0,0 +1,153 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: interactor-validation
3
+ version: !ruby/object:Gem::Version
4
+ version: 0.1.1
5
+ platform: ruby
6
+ authors:
7
+ - Wilson Anciro
8
+ bindir: exe
9
+ cert_chain: []
10
+ date: 1980-01-02 00:00:00.000000000 Z
11
+ dependencies:
12
+ - !ruby/object:Gem::Dependency
13
+ name: activemodel
14
+ requirement: !ruby/object:Gem::Requirement
15
+ requirements:
16
+ - - ">="
17
+ - !ruby/object:Gem::Version
18
+ version: '6.0'
19
+ type: :runtime
20
+ prerelease: false
21
+ version_requirements: !ruby/object:Gem::Requirement
22
+ requirements:
23
+ - - ">="
24
+ - !ruby/object:Gem::Version
25
+ version: '6.0'
26
+ - !ruby/object:Gem::Dependency
27
+ name: activesupport
28
+ requirement: !ruby/object:Gem::Requirement
29
+ requirements:
30
+ - - ">="
31
+ - !ruby/object:Gem::Version
32
+ version: '6.0'
33
+ type: :runtime
34
+ prerelease: false
35
+ version_requirements: !ruby/object:Gem::Requirement
36
+ requirements:
37
+ - - ">="
38
+ - !ruby/object:Gem::Version
39
+ version: '6.0'
40
+ - !ruby/object:Gem::Dependency
41
+ name: interactor
42
+ requirement: !ruby/object:Gem::Requirement
43
+ requirements:
44
+ - - "~>"
45
+ - !ruby/object:Gem::Version
46
+ version: '3.0'
47
+ type: :runtime
48
+ prerelease: false
49
+ version_requirements: !ruby/object:Gem::Requirement
50
+ requirements:
51
+ - - "~>"
52
+ - !ruby/object:Gem::Version
53
+ version: '3.0'
54
+ - !ruby/object:Gem::Dependency
55
+ name: fuubar
56
+ requirement: !ruby/object:Gem::Requirement
57
+ requirements:
58
+ - - "~>"
59
+ - !ruby/object:Gem::Version
60
+ version: '2.5'
61
+ type: :development
62
+ prerelease: false
63
+ version_requirements: !ruby/object:Gem::Requirement
64
+ requirements:
65
+ - - "~>"
66
+ - !ruby/object:Gem::Version
67
+ version: '2.5'
68
+ - !ruby/object:Gem::Dependency
69
+ name: rspec
70
+ requirement: !ruby/object:Gem::Requirement
71
+ requirements:
72
+ - - "~>"
73
+ - !ruby/object:Gem::Version
74
+ version: '3.0'
75
+ type: :development
76
+ prerelease: false
77
+ version_requirements: !ruby/object:Gem::Requirement
78
+ requirements:
79
+ - - "~>"
80
+ - !ruby/object:Gem::Version
81
+ version: '3.0'
82
+ - !ruby/object:Gem::Dependency
83
+ name: rubocop
84
+ requirement: !ruby/object:Gem::Requirement
85
+ requirements:
86
+ - - "~>"
87
+ - !ruby/object:Gem::Version
88
+ version: '1.0'
89
+ type: :development
90
+ prerelease: false
91
+ version_requirements: !ruby/object:Gem::Requirement
92
+ requirements:
93
+ - - "~>"
94
+ - !ruby/object:Gem::Version
95
+ version: '1.0'
96
+ - !ruby/object:Gem::Dependency
97
+ name: simplecov
98
+ requirement: !ruby/object:Gem::Requirement
99
+ requirements:
100
+ - - "~>"
101
+ - !ruby/object:Gem::Version
102
+ version: '0.22'
103
+ type: :development
104
+ prerelease: false
105
+ version_requirements: !ruby/object:Gem::Requirement
106
+ requirements:
107
+ - - "~>"
108
+ - !ruby/object:Gem::Version
109
+ version: '0.22'
110
+ description: Adds Rails-style parameter declaration and validation to Interactor contexts
111
+ with support for presence, format, length, inclusion, and numericality validations.
112
+ email:
113
+ - konekred@gmail.com
114
+ executables: []
115
+ extensions: []
116
+ extra_rdoc_files: []
117
+ files:
118
+ - CHANGELOG.md
119
+ - CODE_OF_CONDUCT.md
120
+ - LICENSE.txt
121
+ - README.md
122
+ - Rakefile
123
+ - lib/interactor/validation.rb
124
+ - lib/interactor/validation/configuration.rb
125
+ - lib/interactor/validation/params.rb
126
+ - lib/interactor/validation/validates.rb
127
+ - lib/interactor/validation/version.rb
128
+ - sig/interactor/validation.rbs
129
+ homepage: https://github.com/zyxzen/interactor-validation
130
+ licenses:
131
+ - MIT
132
+ metadata:
133
+ homepage_uri: https://github.com/zyxzen/interactor-validation
134
+ source_code_uri: https://github.com/zyxzen/interactor-validation
135
+ changelog_uri: https://github.com/zyxzen/interactor-validation/blob/main/CHANGELOG.md
136
+ rdoc_options: []
137
+ require_paths:
138
+ - lib
139
+ required_ruby_version: !ruby/object:Gem::Requirement
140
+ requirements:
141
+ - - ">="
142
+ - !ruby/object:Gem::Version
143
+ version: 3.2.0
144
+ required_rubygems_version: !ruby/object:Gem::Requirement
145
+ requirements:
146
+ - - ">="
147
+ - !ruby/object:Gem::Version
148
+ version: '0'
149
+ requirements: []
150
+ rubygems_version: 3.6.9
151
+ specification_version: 4
152
+ summary: Parameter declaration and validation for Interactor gem
153
+ test_files: []