Created
May 13, 2022 03:20
-
-
Save JoshCheek/2045d2a53657fac3de5cd06ad00d6a59 to your computer and use it in GitHub Desktop.
Rails bug?
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Was super struggling to get my array to validate (nil is bad, empty array is fine, nonempty array should contain strings) | |
# Finally went and read the code, and it looked totally buggy (b/c `nil` is `blank?`: | |
# https://github.com/rails/rails/blob/25b126707152de3a1ec9762ee564f3c7623373b3/activemodel/lib/active_model/validator.rb#L151 | |
# Made this test to demonstrate. | |
require 'active_model' | |
def test(*values, **validation) | |
[false, true].product([false, true]).map.with_index 1 do |(allow_nil, allow_blank), index| | |
klass = Struct.new(:values, keyword_init: true) { include ActiveModel::Validations } | |
klass.validates :values, allow_nil: allow_nil, allow_blank: allow_blank, **validation | |
"%d | allow_blank: %-5p | allow_nil: %-5p | values: #{values.map { "#{_1.inspect}=%-5p" }.join(' ')}" % [ | |
index, allow_nil, allow_blank, *values.map { klass.new(values: _1).valid? }, | |
] | |
end | |
end | |
# 1: blank is not allowed, but `[]` is valid | |
# 2: blank is not allowed, but `[]` is valid | |
# 3: `nil` is not allowed, but is valid | |
test [], nil, length: { minimum: 0 } | |
# => ["1 | allow_blank: false | allow_nil: false | values: []=true nil=false", | |
# "2 | allow_blank: false | allow_nil: true | values: []=true nil=true ", | |
# "3 | allow_blank: true | allow_nil: false | values: []=true nil=true ", | |
# "4 | allow_blank: true | allow_nil: true | values: []=true nil=true "] | |
# 2: blank is not allowed, but `''` is valid | |
# 3: blank is allowed, but is invalid | |
# 3: `nil` is not allowed, but is valid | |
test '', nil, format: /x/ | |
# => ["1 | allow_blank: false | allow_nil: false | values: \"\"=false nil=false", | |
# "2 | allow_blank: false | allow_nil: true | values: \"\"=true nil=true ", | |
# "3 | allow_blank: true | allow_nil: false | values: \"\"=false nil=true ", | |
# "4 | allow_blank: true | allow_nil: true | values: \"\"=true nil=true "] | |
# Some others I tried that were incorrect in the same way as the `format` example | |
test [], nil, presence: true | |
test [], nil, acceptance: true |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment