You get this warning because 'if' is a macro which compiles into a
'case' statement. The way that case statements and scoping works, you
*can* assign to variables outside of the case statement from inside, but
it is generally considered not-good practice to do so, thus the compiler
warnings.
If you had written your code like this:
{id, update_timestamp} =
if !my_object do
{ nil, Date.now |> DateFormat.format!("{ISOz}") }
else
{
my_object.id, my_object.update_timestamp }
end
You would get the same effect, but without the warning.
You could also rewrite this using pattern matching inside a case statement:
{id, update_timestamp} =
case my_object do
nil ->
{ nil, Date.now |> DateFormat.format!("{ISOz}") }
%{id: id, update_timestamp: update_timestamp} ->
{ id, update_timestamp }
end
which might read better depending on one's preferences. I would also
recommend moving the timestamp initializing to a separate function to
keep things clean and readable.
Gilbert