Help me harden this "format_date" function for my Phoenix templates?

I have this function in my helpers.ex file:

def format_date(nil), do: nil
def format_date(""), do: ""

def format_date(date) do
  "#{date.day}/#{date.month}/#{date.year}"
end

I use it:

<span><%= format_date(@record.inserted_at) %></span>

I wanted to use a guard clause to only go into the function is is_datetime, but such a function doesn’t exist.

How can I harden this function?

image

Kernel.is_struct/2

1 Like
def format_date(date) when is_struct(date, DateTime) do
  "#{date.day}/#{date.month}/#{date.year}"
end

Bombastic :fire:

Two thoughts:

  • What specifically are you aiming for with “hardening”? For instance, the suggested is_struct guard will only move the crash site from date.day to format_date in this call:

    <span><%= format_date(%NotADateTime{foo: "bar"}) %></span>
    
  • guarding on the specific type for datetimes is a minefield, since there are multiple types that can otherwise be mixed (Date, DateTime, NaiveDateTime). Consider matching on the fields your code needs and using types like Calendar.date

2 Likes