How to assign a function to a specific version of Elixir

Hello, I have a library that I want to update it and add some features, but some of my user do not want to update their elixir version.
Then there is a question how can I add some function to my module when old version elixir users load it, they see an error like “you can not load this function because you have older elixir version” and they are not able to use these functions.

# if elixir > 1.10.2
def hi(), do: IO.inspect("hi new elixir")

# for all version of elixir
def hi(_params), do: IO.inspect("hi all elixir versions")

And how to do it on my tests to skip function which use new elixir that my user doesn’t have it?

Thanks.

In general its better to test the capabilities of the Elixir version, rather than the version itself. Here’s one example from one of my libs. Basically it checks for a particular function signature that is known to be different between two versions of Elixir. But the version itself doesn’t matter.

There is one case where I’ve had to resort to actually testing an library version and that was during the transition from Decimal version 1.9 to 2.0.

You can test, at compile time, the version of a library like this (with decimal as the example):

iex> decimal_version = Application.ensure_all_started(:decimal) && Application.spec(:decimal, :vsn) |> List.to_string()
"2.0.0"

For Elixir you can do:

iex> System.version()
"1.12.0"

For comparing versions you can do the following, using the same match specs as you do for dependencies.

iex> Version.match?(decimal_version, "~> 1.6 or ~> 1.9.0-rc or ~> 1.9")
false
7 Likes