Coming from C language paradigm to ruby, unless might seem just the “awesome” feature which was missing in C.
Here are some examples highlighting the beauty:
1. When used as a Statement modifier
raise InvalidData unless AllowedDatum.include?(data)
looks much better than
raise InvalidData if !AllowedDatum.include?(data)
2. When used without else
unless condition #code block end
looks much better than
if !condition #code block end
However the problem with using unless starts when we have the following two cases
3. using unless with else
unless condition #code block 1 else #code block 2 end
is difficult to understand than
if condition #code block 2 else #code block 3 end
4. Concatenation of conditions
unless condition_1 || condition_2
has to be always deciphered into
if !condition_1 && !condition_2
to get a feeling of whats happening
However using !condition takes the beauty out of your code. For example
if !element.nil? && !allowedParams.include?(element)
is not as beautiful and readable as
elem.call_method unless elem.blank?
To solve the above problem we at intinno have a following mixin defined:
class Object
def not_nil?
!nil?
end
def not_blank?
!blank?
end
def not_eql?(value)
!eql?(value)
end
def not_empty?
!empty?
end
def not_included?
!included?
end
end
An example of using the above mixin is
if element.not_nil? && allowedParams.doesnt_include?(element)
Now our code looks like Angelina Jolie and is as readable as any of Chetan Bhaghat’s novels.
