def func1(arg1) do
MyAppWeb.ErrorView.some_method(arg1) # works well
end
Now I want to move the mentod into a library which I’ll use in multiple apps of mine. How would I access MyAppWeb.ErrorView. from a library?
# my library
def func1(arg1) do
# how to refer to the current app/client which uses this lib?
# And thus access its ErrorView module
# SomeApp????Web.ErrorView.some_method(arg1) # ???
end
It is irrelevant whether or not a module is from the current application or another one that came as a dependency.
You can just use the fully qualified module name as you do in your example or you can use alias to alias the module name and then use that alias instead.
Also please remember, in elixir we do not have “methods” only functions.
In my example it was for a concreate module and as an example. Which won’t be the case for a library.
A library can’t know the fully qualified name of an app – an app which happens to use a library.
Module and functions have names. You do not need to know the name of the app of your dependency, you just call functions.
If though you want your dependency know about your current application you are developing, either give that information as config values or additional arguments to the function you are calling.
No exactly.
I want to call a function of an app from within a dependency.
How can I call a function if a fuction can’t be called without the fullyqualified name? Unless it’s been “import”, which isn’t the case for my example.
the fully qualified name can’t be known to a library because any app could happen to use a library.
How can I pass the name of a module as an argument and then use it to call a function on it?
You need to configure the dependency then to know the module and function to call and read from within that dependency the configuration and then call.
This is a pretty standard callback strategy.
There are several ways to do the configuration necessary, which one you should use depends on your actual use case.
receive_mod = fn mod -> mod.some_function() end
receive_mod.(MyModule)
# or
receive_mod_and_fun = fn mod, fun -> apply(mod, fun, [1, 2]) end
receive_mod_and_fun.(MyModule, :add)