Today I Learned

hashrocket A Hashrocket project

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
See More #elixir TILs
Looking for help? At Hashrocket, we 💜 Elixir! From our many Elixir client projects, to sponsoring the Chicago Elixir Meetup, to the source code for this application, we are invested in this community. Contact us today to talk about your Elixir project.