if Version.match?("#{Application.spec(:phoenix_live_view, :vsn)}", "~> 0.18") do
import Phoenix.Component, only: [assign: 3, assign_new: 3]
else
import Phoenix.LiveView, only: [assign: 3, assign_new: 3]
end
seems to be evaluated at runtime… and needs to be handled by the compiler first.
** (CompileError) lib/somefile.ex:4: module Phoenix.Component is not loaded and could not be found
(stdlib 3.17.2.1) lists.erl:1358: :lists.mapfoldl/3
(stdlib 3.17.2.1) lists.erl:1359: :lists.mapfoldl/3
(stdlib 3.17.2.1) lists.erl:1358: :lists.mapfoldl/3
(elixir 1.13.4) expanding macro: Kernel.if/2
For this you need a macro. Here is an example script:
# required minimal config to fix warnings
Application.put_env(:phoenix, :json_library, Jason)
# we also need to install json library dependency
# and one of phoenix_live_view versions
Mix.install([:jason, phoenix_live_view: "~> 0.17.0"])
# or
Mix.install([:jason, phoenix_live_view: "~> 0.18"])
defmodule MyLib do
defmacro my_macro(app, version_match, opts) do
vsn = app |> Application.spec(:vsn) |> List.to_string()
if Version.match?(vsn, version_match), do: opts[:do], else: opts[:else]
end
end
defmodule Example do
require MyLib
MyLib.my_macro :phoenix_live_view, "~> 0.18" do
import Phoenix.Component, only: [assign: 3, assign_new: 3]
else
import Phoenix.LiveView, only: [assign: 3, assign_new: 3]
end
end