Pattern match against Dates in Elixir using struct
A recent TIL by my coworker Ryan reminded me of an alternative to pattern matching on dates (and other structs) by matching on their Name.
Using __struct__
to grab the name allows us to use a guard and only match on struct types we want:
def foo(%{__struct__: struct_name} = datetime)
when struct_name in [Date, DateTime] do
Timex.to_naive_datetime(datetime) |> foo
end
def foo(%NaiveDateTime{} = datetime) do
IO.inspect({"My Naive Datetime", datetime})
end
Tweet