soft_validator 1.0.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: 64db8fb56e161e44e7a584528a2c8dd5831ce1c6e10f77d0a02305ff51ae2aea
4
+ data.tar.gz: 403ef75272880d067ab2657ae678bee52b7f9ff3d1297230e1ed8ae5b7025227
5
+ SHA512:
6
+ metadata.gz: 7e62f0f978d8850a29119294f1a56cc6b52d0114c093644f7d61cb893feb5998e1ff9916d90c58be37bd6e9b5105e58943adee8b8ae8836fda06c8350864d68b
7
+ data.tar.gz: 9bcbfe1be63d91adad556557b50cb6dfa2babe13b851df51f3cd0fd1869cd14652dbc36d3945a1c004d6df14388a14412ddfe7e39e1bc189db7603f10292495a
data/CHANGELOG.md ADDED
@@ -0,0 +1,11 @@
1
+ # Changelog
2
+ All notable changes to this project will be documented in this file.
3
+
4
+ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
5
+ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
6
+
7
+ ## 1.0.0
8
+
9
+ ### Added
10
+
11
+ - Initial release
data/MIT_LICENSE.txt ADDED
@@ -0,0 +1,20 @@
1
+ Copyright (c) 2023 Brian Durand
2
+
3
+ Permission is hereby granted, free of charge, to any person obtaining
4
+ a copy of this software and associated documentation files (the
5
+ "Software"), to deal in the Software without restriction, including
6
+ without limitation the rights to use, copy, modify, merge, publish,
7
+ distribute, sublicense, and/or sell copies of the Software, and to
8
+ permit persons to whom the Software is furnished to do so, subject to
9
+ the following conditions:
10
+
11
+ The above copyright notice and this permission notice shall be
12
+ included in all copies or substantial portions of the Software.
13
+
14
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
15
+ EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
16
+ MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
17
+ NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
18
+ LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
19
+ OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
20
+ WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
data/README.md ADDED
@@ -0,0 +1,109 @@
1
+ # SoftValidator
2
+
3
+ [![Continuous Integration](https://github.com/bdurand/soft_validator/actions/workflows/continuous_integration.yml/badge.svg)](https://github.com/bdurand/soft_validator/actions/workflows/continuous_integration.yml)
4
+ [![Regression Test](https://github.com/bdurand/soft_validator/actions/workflows/regression_test.yml/badge.svg)](https://github.com/bdurand/soft_validator/actions/workflows/regression_test.yml)
5
+ [![Ruby Style Guide](https://img.shields.io/badge/code_style-standard-brightgreen.svg)](https://github.com/testdouble/standard)
6
+ [![Gem Version](https://badge.fury.io/rb/soft_validator.svg)](https://badge.fury.io/rb/soft_validator)
7
+
8
+ This gem adds a soft validator for use with ActiveModel/ActiveRecord. It is intended to solve issues that can arise when adding new validations to an existing model. Once your model is running in production and taking real world inputs, it can be risky to add a new validation since it might break some of those inputs. This gem allows you to soft launch a new validation by running it in a non-enforcing mode. This will allow you to see what would have failed without actually failing the validation. You can then fix the issues and turn on the validation.
9
+
10
+ ## Usage
11
+
12
+ The easiest way to use the gem is simply to wrap your existing validations with a `:soft` validation.
13
+
14
+ ```ruby
15
+ class Thing < ApplicationRecord
16
+ validates :units, presence: true, soft: {inclusion: {in: ["feet", "meters"]}}
17
+ end
18
+ ```
19
+
20
+ Each of the validations in the `:soft` validation will still be run when the record is validated. However, if there are any errors, they will not be added to the record `errors` object and the record will still be considered valid.
21
+
22
+ ### Notifications
23
+
24
+ Soft validation errors are published via ActiveSupport notifications. You can handle errors generted from soft validations by subscribing to the `validation_error.soft_validator` event. For instance, you could log the errors to the Rails logger by adding this code to an initializer:
25
+
26
+ ```ruby
27
+ ActiveSupport::Notifications.subscribe("validation_error.soft_validator") do |event|
28
+ error = event.payload[:error]
29
+ message = "Soft validation error on {error.base.class.name}(#{error.base.id}): #{error.full_message}"
30
+ Rails.logger.warn(message)
31
+ end
32
+ ```
33
+
34
+ You can also the `SoftValidator.subscribe` helper method to set up subscriptions. This code will do the same thing as the code above:
35
+
36
+ ```ruby
37
+ SoftValidator.subscribe do |error|
38
+ message = "Soft validation error on {error.base.class.name}(#{error.base.id}): #{error.full_message}"
39
+ Rails.logger.warn(message)
40
+ end
41
+ ```
42
+
43
+ If you just want to log the errors, you can use the built in log subscriber instead (it does the same thing as the above subscription). You **do not** need to do this in a Rails application; it will be done for you automatically.
44
+
45
+ ```ruby
46
+ SoftValidator::LogSubscriber.attach
47
+ ```
48
+
49
+ You can disable the log subscriber by calling `SoftValidator::LogSubscriber.detach`.
50
+
51
+ ### Enforcing with feature flags
52
+
53
+ You can turn a soft validation into a hard validation by setting the `:enforce` option to `true`. This will cause the validation to generate errors as normal. You can use this option to enable validation with a feature flag.
54
+
55
+ ```ruby
56
+ class Thing < ApplicationRecord
57
+ validates :units,
58
+ presence: true,
59
+ soft: {
60
+ inclusion: {in: ["feet", "meters"]},
61
+ enforce: ENV.fetch("ENFORCE_UNITS", !Rails.env.production?.to_s) == "true"
62
+ }
63
+ end
64
+ ```
65
+
66
+ The global default for enforcing soft validations can be changed by setting `SoftValidator.enforce`. If it is set to `true`, soft validations will be enforced by default. In Rails applications this is set automatically in the development and test environments since you would typically want to see the errors in those environments so that you can fix them.
67
+
68
+ ### Conditional options
69
+
70
+ If you want to add any of the standard conditional options for the validator (i.e. `:if`, `:unless`, `:on`, `:prepend`), you need to add it to the soft validator and not the wrapped validator.
71
+
72
+ ```ruby
73
+ class Thing < ApplicationRecord
74
+ validates :units,
75
+ soft: {inclusion: {in: ["feet", "meters"]}, if: :units_changed?}
76
+
77
+ # This won't work; the `if` option cannot be on the wrapped validator:
78
+ # validates :units,
79
+ # soft: {inclusion: {in: ["feet", "meters"], if: :units_changed?}}
80
+ end
81
+ ```
82
+
83
+ ## Installation
84
+
85
+ Add this line to your application's Gemfile:
86
+
87
+ ```ruby
88
+ gem "soft_validator"
89
+ ```
90
+
91
+ Then execute:
92
+ ```bash
93
+ $ bundle
94
+ ```
95
+
96
+ Or install it yourself as:
97
+ ```bash
98
+ $ gem install gem "soft_validator"
99
+ ```
100
+
101
+ ## Contributing
102
+
103
+ Open a pull request on GitHub.
104
+
105
+ Please use the [standardrb](https://github.com/testdouble/standard) syntax and lint your code with `standardrb --fix` before submitting.
106
+
107
+ ## License
108
+
109
+ The gem is available as open source under the terms of the [MIT License](https://opensource.org/licenses/MIT).
data/VERSION ADDED
@@ -0,0 +1 @@
1
+ 1.0.0
@@ -0,0 +1,32 @@
1
+ # frozen_string_literal: true
2
+
3
+ # Log subscriber for soft validation errors.
4
+ class SoftValidator::LogSubscriber < ActiveSupport::LogSubscriber
5
+ class << self
6
+ # Helper method to attach the log subscriber.
7
+ def attach
8
+ attach_to :soft_validator
9
+ end
10
+
11
+ # Helper method to detach the log subscriber.
12
+ def detach
13
+ detach_from :soft_validator
14
+ end
15
+ end
16
+
17
+ def validation_error(event)
18
+ return unless logger&.warn?
19
+
20
+ error = event.payload[:error]
21
+ record = error.base
22
+ ref = record.class.name
23
+ ref = "#{ref}(#{record.id})" if record.respond_to?(:id)
24
+ message = "Soft validation error on #{ref}: #{error.full_message}"
25
+
26
+ logger.warn(message)
27
+ end
28
+
29
+ def logger
30
+ self.class.logger
31
+ end
32
+ end
@@ -0,0 +1,8 @@
1
+ # frozen_string_literal: true
2
+
3
+ class SoftValidator::Railtie < Rails::Railtie
4
+ initializer("soft_validator.initialize") do
5
+ SoftValidator::LogSubscriber.attach
6
+ SoftValidator.enforced = (Rails.env.development? || Rails.env.test?)
7
+ end
8
+ end
@@ -0,0 +1,70 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "active_model"
4
+
5
+ class SoftValidator < ActiveModel::EachValidator
6
+ VERSION = File.read(File.join(__dir__, "..", "VERSION")).strip.freeze
7
+
8
+ ERROR_EVENT = "validation_error.soft_validator"
9
+
10
+ class << self
11
+ def enforced?
12
+ @enforced ||= false
13
+ end
14
+
15
+ attr_writer :enforced
16
+
17
+ def subscribe(&block)
18
+ ActiveSupport::Notifications.subscribe(ERROR_EVENT) do |event|
19
+ yield(event.payload[:error])
20
+ end
21
+ end
22
+ end
23
+
24
+ def initialize(options)
25
+ super
26
+ @validators = wrapped_validators(options[:class])
27
+ end
28
+
29
+ def validate_each(record, attribute, value)
30
+ existing_errors = record.errors.errors.dup
31
+ @validators.each do |validator|
32
+ validator.validate_each(record, attribute, value)
33
+ next if enforced?
34
+
35
+ (record.errors.errors - existing_errors).each do |error|
36
+ record.errors.delete(error.attribute, error.type, **error.options)
37
+ ActiveSupport::Notifications.instrument(ERROR_EVENT, error: error)
38
+ end
39
+ end
40
+ end
41
+
42
+ def enforced?
43
+ enforced = options[:enforced]
44
+ enforced = enforced.call if enforced.is_a?(Proc)
45
+ enforced || self.class.enforced?
46
+ end
47
+
48
+ private
49
+
50
+ def wrapped_validators(klass)
51
+ options.except(:enforced, :if, :unless, :on).map do |validator_name, validator_options|
52
+ class_name = "#{validator_name.to_s.camelize}Validator"
53
+
54
+ begin
55
+ validator = klass.const_get(class_name)
56
+ rescue NameError
57
+ raise ArgumentError, "Unknown validator: '#{class_name}'"
58
+ end
59
+
60
+ validator_options = {} unless validator_options.is_a?(Hash)
61
+ validator.new(validator_options.merge(class: klass, attributes: attributes))
62
+ end
63
+ end
64
+ end
65
+
66
+ require_relative "soft_validator/log_subscriber"
67
+
68
+ if defined?(Rails::Railtie)
69
+ require_relative "soft_validator/railtie"
70
+ end
@@ -0,0 +1,36 @@
1
+ Gem::Specification.new do |spec|
2
+ spec.name = "soft_validator"
3
+ spec.version = File.read(File.join(__dir__, "VERSION")).strip
4
+ spec.authors = ["Brian Durand"]
5
+ spec.email = ["bbdurand@gmail.com"]
6
+
7
+ spec.summary = "ActiveModel/ActiveRecord validator that can wrap other validators to notify of errors so that new validations can be safely added to an existing model."
8
+ spec.homepage = "https://github.com/bdurand/soft_validator"
9
+ spec.license = "MIT"
10
+
11
+ # Specify which files should be added to the gem when it is released.
12
+ # The `git ls-files -z` loads the files in the RubyGem that have been added into git.
13
+ ignore_files = %w[
14
+ .
15
+ Appraisals
16
+ Gemfile
17
+ Gemfile.lock
18
+ Rakefile
19
+ config.ru
20
+ assets/
21
+ bin/
22
+ gemfiles/
23
+ spec/
24
+ ]
25
+ spec.files = Dir.chdir(__dir__) do
26
+ `git ls-files -z`.split("\x0").reject { |f| ignore_files.any? { |path| f.start_with?(path) } }
27
+ end
28
+
29
+ spec.require_paths = ["lib"]
30
+
31
+ spec.add_dependency "activemodel", ">= 7.0"
32
+
33
+ spec.add_development_dependency "bundler"
34
+
35
+ spec.required_ruby_version = ">= 2.7"
36
+ end
metadata ADDED
@@ -0,0 +1,80 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: soft_validator
3
+ version: !ruby/object:Gem::Version
4
+ version: 1.0.0
5
+ platform: ruby
6
+ authors:
7
+ - Brian Durand
8
+ autorequire:
9
+ bindir: bin
10
+ cert_chain: []
11
+ date: 2024-03-29 00:00:00.000000000 Z
12
+ dependencies:
13
+ - !ruby/object:Gem::Dependency
14
+ name: activemodel
15
+ requirement: !ruby/object:Gem::Requirement
16
+ requirements:
17
+ - - ">="
18
+ - !ruby/object:Gem::Version
19
+ version: '7.0'
20
+ type: :runtime
21
+ prerelease: false
22
+ version_requirements: !ruby/object:Gem::Requirement
23
+ requirements:
24
+ - - ">="
25
+ - !ruby/object:Gem::Version
26
+ version: '7.0'
27
+ - !ruby/object:Gem::Dependency
28
+ name: bundler
29
+ requirement: !ruby/object:Gem::Requirement
30
+ requirements:
31
+ - - ">="
32
+ - !ruby/object:Gem::Version
33
+ version: '0'
34
+ type: :development
35
+ prerelease: false
36
+ version_requirements: !ruby/object:Gem::Requirement
37
+ requirements:
38
+ - - ">="
39
+ - !ruby/object:Gem::Version
40
+ version: '0'
41
+ description:
42
+ email:
43
+ - bbdurand@gmail.com
44
+ executables: []
45
+ extensions: []
46
+ extra_rdoc_files: []
47
+ files:
48
+ - CHANGELOG.md
49
+ - MIT_LICENSE.txt
50
+ - README.md
51
+ - VERSION
52
+ - lib/soft_validator.rb
53
+ - lib/soft_validator/log_subscriber.rb
54
+ - lib/soft_validator/railtie.rb
55
+ - soft_validator.gemspec
56
+ homepage: https://github.com/bdurand/soft_validator
57
+ licenses:
58
+ - MIT
59
+ metadata: {}
60
+ post_install_message:
61
+ rdoc_options: []
62
+ require_paths:
63
+ - lib
64
+ required_ruby_version: !ruby/object:Gem::Requirement
65
+ requirements:
66
+ - - ">="
67
+ - !ruby/object:Gem::Version
68
+ version: '2.7'
69
+ required_rubygems_version: !ruby/object:Gem::Requirement
70
+ requirements:
71
+ - - ">="
72
+ - !ruby/object:Gem::Version
73
+ version: '0'
74
+ requirements: []
75
+ rubygems_version: 3.4.10
76
+ signing_key:
77
+ specification_version: 4
78
+ summary: ActiveModel/ActiveRecord validator that can wrap other validators to notify
79
+ of errors so that new validations can be safely added to an existing model.
80
+ test_files: []