Custom functions with regex patternmatch

Hello, everyone.

Api i want is execute("some text", %{some: :data})

The first parameter is a binary string, the second parameter is a map with extra data.

registering executable code block:

executable ~r/here goes regex/, herer_goes_named_captures, here_goes_map_with_extra_data do
  # Here goes executable block
end

so the first parameter passed to execute would be regex matched and named captures extracted from that text. than named_captures with the second parameter would be given to executable block.

herer_goes_named_captures and here_goes_map_with_extra_data can also be patternmatches, like %{matched_key: "value"}.

executable ~r/here goes regex/, %{named_capture_key: value}, %{not_existing_key: "exact value"} do
  # Here goes executable block
end

execute function goes through all registered executables till finds one with matching regex, and then with matching patterns provided with herer_goes_named_captures and here_goes_map_with_extra_data. If something doesn’t match, continues iterate over executables, till finds something that actually matches or reaches the end. If the end is reached throws an error “no implementation found”.

Thanks for the help :slight_smile: and have a great day.
Roberts.

As long as execute/2 and the executable/4 are in the same module, you could look at the implementation of the test/3-macro to get an idea about how to map those into functions, names derived from the regex.

Then you also collect all the regexes in a module attribute of your choice (eg. @__executors__). From those you build a giant cond in the execute function (which you also need to generate) which simply delegates to the functions generated by executor.

Thats the rough idea. But before going into this, I’d recommend to give Metaprogramming Elixir a read, you’ll need it…

1 Like