Ruby: return value or zero

I have this method in Rails and it works in the transmission parameter date_string, nil. In particular, when it GetFileInfo -dreturns nil.

What is the way Rails-y 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

OK to return zero from this, assuming it Model.create(creation_date: return_value_here)can handle nil values.

Edit: Added some other methods to illustrate the call chain.

+4
source share
5 answers

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?, this is the exact opposite .blank?)

+2

, Ruby :

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

, :

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

return Ruby. , Java, return, .

+1

, , date_string . If,

def local_datetime_for(date_string)
  if date_string === nil
    t = Time.strptime(date_string, '%m/%d/%Y %H:%M:%S')
    t = DateTime.parse(t.to_s)
  else
    t = 'Unknown'
  end
  return t
end
0

date_string. - - nil?, , Ruby-ish:

def local_datetime_for(date_string)
  return if date_string.nil?
  t = Time.strptime(date_string, '%m/%d/%Y %H:%M:%S') 
  DateTime.parse(t.to_s)
end

" " - - , , , , .

0

Use File.statinstead of calling the system for GetFileInfo. Then handle any exceptions with help statin Ruby that could lead to a result nil.

def cdate_for(path)
  File.stat(path).ctime.to_datetime
end
0
source

All Articles