Ruby: return value or nil
Solution 1
You can use .blank?
:
def local_datetime_for(date_string)
return nil if date_string.blank?
t = Time.strptime(date_string, '%m/%d/%Y %H:%M:%S')
DateTime.parse(t.to_s)
end
Some use cases for .blank?
:
1.9.3p448 :042 > false.blank?
=> true
1.9.3p448 :043 > true.blank?
=> false
1.9.3p448 :044 > [].blank?
=> true
1.9.3p448 :045 > ''.blank?
=> true
1.9.3p448 :046 > '1'.blank?
=> false
1.9.3p448 :047 > nil.blank?
=> true
(For the record, .present?
is the exact opposite of .blank?
)
Solution 2
I think idiomatic Ruby calls for this:
def local_datetime_for(date_string)
unless date_string.blank?
t = Time.strptime(date_string, '%m/%d/%Y %H:%M:%S')
DateTime.parse(t.to_s)
end
end
Or if you want to be fancy:
def local_datetime_for(date_string)
DateTime.parse(Time.strptime(date_string, '%m/%d/%Y %H:%M:%S').to_s) unless date_string.blank?
end
Using return
early in the method is very Ruby too. I just have trouble getting used to it coming from a Java background where I avoided early return
s like the plague.
Solution 3
Use File.stat
instead of calling out to the system for GetFileInfo
. Then handle any exceptions with the stat
in Ruby that might have caused a nil
result.
def cdate_for(path)
File.stat(path).ctime.to_datetime
end
Meltemi
Updated on June 04, 2022Comments
-
Meltemi almost 2 years
I have this method in Rails and it trips up when passed in parameter,
date_string
, isnil
. Specifically whenGetFileInfo -d
returns nil.What's a Rails-y way to handle this?
def calling_method ... m = MyModel.create(creation_date: cdate_for(path)) ... end def cdate_for(path) local_datetime_for(`GetFileInfo -d "#{path}"`.chomp!) end def local_datetime_for(date_string) t = Time.strptime(date_string, '%m/%d/%Y %H:%M:%S') DateTime.parse(t.to_s) end
It's OK to return nil from this, assuming
Model.create(creation_date: return_value_here)
can handle nil values.Edit: added some other methods to illustrate call chain.
-
Meltemi over 10 yearsadded some other methods to illustrate the call chain. Trying to avoid wrapping things in
if
statements. Doesn't feel very "Rails-y"... perhaps I'm over thinking... -
RobertMcAtee over 10 years@MrYoshiji 's answer using return nil if looks perhaps a little more "rubish". Also I know the code above is just a sample but just in case it is a copy of the code, I would recommend including "return"s