Boris Okner
Boris Okner

Reputation: 330

Elixir: generating catch-all function calls

I have a macro that puts catch-all functions in the end of the module, so resulting module looks something like:

defmodule Module1 do
   <module body>
   ## Generated catch-all functions
   def fun1(_, _), do: :ok
   ## ..more catch-all functions...##
end ## of module

The problem I'm trying to solve is to suppress warnings

"this clause cannot match because a previous clause at line XX always matches" in case the user of macro will have, for instance

   def fun1(arg1, arg2), do: ...

in the body of the module.

I guess I can go through module's body AST and do some analysis of function signatures before generating catch-all functions, but it seems to be a lot of work. Is there any other way?

Upvotes: 2

Views: 977

Answers (1)

Miroslav Prymek
Miroslav Prymek

Reputation: 1803

(I think you know this solution but maybe it could be useful to other SO users to answer this question :) )

As José have said, it's not a very good practice to hide too much in the code as it can lead to surprises (hidden code can do something you do not expect t to do) and can even limit you (in this particular case, if you have un-explicit catchall, you can't get rid of it...).

I thing the best approach is to explicitly use a macro to generate all the boilerplate code. One line to call the macro is not as much boilerplate ;)

Example implementation: https://gist.github.com/mprymek/73f878e103f60d6d89e2

Upvotes: 1

Related Questions