Replace null values with zero values in ruby on rauls '
nil.to_i
=> 0
nil.to_f
=> 0.0
..........
=> []
irb(main):002:0> value = array[0] || 0
=> 0
irb(main):003:0> value
=> 0Hope this helps,
.........
use :null => false
change_column :my_table, :my_column, :integer, :default => 0, :null => false
null to no effects
change_column will not query to replace the null values when you change null to false, even if you have a default set. This may cause the query to fail (may depend on the database used).
change_column_null will optionally take a value to replace nulls if you are setting null to false. If you want to set a default and disallow nulls you likely can’t do both in one change_column call.
to set NULL => NO
use :null => false
change_column :my_table, :my_column, :integer, :default => 0, :null => false
https://refactoring.guru/introduce-null-object
Why Refactor
Dozens of checks for null make your code longer and uglier.
Drawbacks
- The price of getting rid of conditionals is creating yet another new class.
How to Refactor
-
From the class in question, create a subclass that will perform the role of null object.
-
In both classes, create the method isNull(), which will return true for a null object and false for a real class.
-
Find all places where the code may return null instead of a real object. Change the code so that it returns a null object.
-
Find all places where the variables of the real class are compared with null. Replace these checks with a call for isNull().
-
- If methods of the original class are run in these conditionals when a value doesn’t equal
null, redefine these methods in the null class and insert the code from the else
part of the condition there. Then you can delete the entire conditional
and differing behavior will be implemented via polymorphism. - If
things aren’t so simple and the methods can’t be redefined, see if you
can simply extract the operators that were supposed to be performed in
the case of a
null value to new methods of the null object. Call these methods instead of the old code in else as the operations by default.
Comments
Post a Comment