Skip to content

Commit

Permalink
Merge pull request #18 from ahoshaiyan/fix-defaults-for-boolean
Browse files Browse the repository at this point in the history
Fix defaults with boolean types
  • Loading branch information
ahoshaiyan authored Jun 11, 2024
2 parents 73c868d + 8309364 commit a6ab06b
Show file tree
Hide file tree
Showing 4 changed files with 34 additions and 4 deletions.
2 changes: 1 addition & 1 deletion lib/mini_defender/validates_input.rb
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ def validate!(rules, coerced = false)
data = cleanse_data(params.to_unsafe_hash.deep_stringify_keys)
validator = MiniDefender::Validator.new(rules, data)
validator.validate!
coerced ? validator.coerced : validator.data
coerced ? validator.coerced : validator.validated
end

private
Expand Down
11 changes: 9 additions & 2 deletions lib/mini_defender/validator.rb
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ def validate

# Set default values for missing data key compared to rules
data_rules.each do |k, set|
if !@data.key?(k) || @data[k].blank?
if !@data.key?(k) || missing_value?(@data[k])
set.filter{ |r| r.defaults?(self) }.each do |r|
@data.merge!({k => r.default_value(self)}.flatten_keys(keep_roots: true))
end
Expand All @@ -43,7 +43,7 @@ def validate
value_included = true
required = rule_set.any? { |r| r.implicit?(self) }

if !@data.key?(k) || @data[k].blank?
if !@data.key?(k) || missing_value?(@data[k])
rule_set.filter{ |r| r.defaults?(self) }.each do |r|
@data.merge!({k => r.default_value(self)}.flatten_keys(keep_roots: true))
end
Expand Down Expand Up @@ -188,5 +188,12 @@ def compact_keys(hash, current_key = '')

result
end

def missing_value?(value)
value.nil? ||
value.is_a?(String) && value.strip.empty? ||
value.is_a?(Hash) && value.empty? ||
value.is_a?(Array) && value.empty?
end
end
end
2 changes: 1 addition & 1 deletion lib/mini_defender/version.rb
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
# frozen_string_literal: true

module MiniDefender
VERSION = "0.6.1"
VERSION = "0.6.2"
end
23 changes: 23 additions & 0 deletions test/validator_test.rb
Original file line number Diff line number Diff line change
Expand Up @@ -115,4 +115,27 @@ def test_should_return_neighbors_of_key_in_array
}
)
end

def test_only_validated_data_should_be_returned
v = MiniDefender::Validator.new(
{
'address' => 'required|hash',
'address.is_personal' => 'required|boolean|default:true',
},
{
'address' => {
'is_personal' => false
},
'name' => 'John Doe'
}
)

v.validate!
data = v.validated

assert_equal 1, data.length
assert data['address'].is_a?(Hash)
assert data['address'].key?('is_personal')
assert data['address']['is_personal'].is_a?(FalseClass)
end
end

0 comments on commit a6ab06b

Please sign in to comment.