Turn off warning redefining module String.Chars.NaiveDateTime

I am overriding to_string for naive datetime’s like so:

defimpl String.Chars, for: NaiveDateTime do
  def to_string(term) do
    Timex.format!(term, "{ISOdate} {ISOtime}")
  end
end

But then I get this warning:

warning: redefining module String.Chars.NaiveDateTime (current version loaded from /usr/local/Cellar/elixir/1.13.2/bin/../lib/elixir/ebin/Elixir.String.Chars.NaiveDateTime.beam)
  lib/supermanager/string/chars.ex:1

Which comes from here:

Is it possible to suppress this warning?

Or is it better to not use to_string in this case?

Protocols are not designed to be overridden - the whole idea of a protocol is that the behaviour is bound to the datatype. What is the problem you have and what are you trying to achieve?

FWIW your Timex format is the same as the output for a NaiveDateTime using Calendar.ISO (the default):

iex> NaiveDateTime.local_now |> then(&(Timex.format!(&1, "{ISOdate} {ISOtime}") == to_string(&1)))
true

You can also format NaiveDateTimes natively without Timex by using Calendar.strftime/3:

iex> NaiveDateTime.local_now |> Calendar.strftime("%c")
"2022-02-20 17:13:06"
4 Likes

What is the problem you have and what are you trying to achieve?

Polymorphism. I would like to have one way to convert data types to a human readable value, so I can display them in the UI without having to worry about the exact datatype.

FWIW your Timex format is the same as the output for a NaiveDateTime using Calendar.ISO (the default):

Sweet, I didn’t know. I settled on creating a new protocol for now:

defprotocol Humanize do
  def to_human(term)
end

Maybe that is better anyway, messing with to_string might not be such a good idea (I come from Ruby btw where monkey patching is all over the place :smile:)

1 Like

:+1: This is the way to go. There will be no surprises to anyone coming to the codebase that there’s something strange about how to_string works.

1 Like