Class: BlockKit::Fixers::NullValue
- Defined in:
- lib/block_kit/fixers/null_value.rb
Instance Method Summary collapse
- #fix(model, fixing_dangerously: false) ⇒ Object
-
#initialize(attribute:, **options) ⇒ NullValue
constructor
A new instance of NullValue.
Methods inherited from Base
Constructor Details
#initialize(attribute:, **options) ⇒ NullValue
Returns a new instance of NullValue.
8 9 10 11 12 |
# File 'lib/block_kit/fixers/null_value.rb', line 8 def initialize(attribute:, **) super @error_types = .delete(:error_types) { [:blank] } end |
Instance Method Details
#fix(model, fixing_dangerously: false) ⇒ Object
14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 |
# File 'lib/block_kit/fixers/null_value.rb', line 14 def fix(model, fixing_dangerously: false) return if dangerous? && !fixing_dangerously model.validate errors = errors_for(model) return unless errors.any? { |e| error_types.include?(e.type) } value = model.attributes[attribute.to_s] # First, check if the attribute is an array and if we have an `inclusion` error. # If so, we'll remove invalid values from the array. If the new value is empty # and this fixer is configured to handle `blank` errors, we'll nullify it. if value.is_a?(Enumerable) && (error = errors.find { |e| e.type == :inclusion }) new_value = value - error.[:invalid_values] new_value = new_value.presence if error_types.include?(:blank) model.assign_attributes(attribute => new_value) else model.assign_attributes(attribute => nil) end end |