Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pattern match on end of a string/binary argument

Tags:

elixir

I'm currently writing a little test runner in Elixir. I want to use pattern matching to evaluate if a file is in the spec format (ending in "_spec.exs"). There are numerous tutorials on how to pattern match on the beginning of a string, but that somehow won't work on string endings:

defp filter_spec(file <> "_spec.exs") do
  run_spec(file)
end

defp run_spec(file) do
  ...
end

This always ends up in the compilation error:

== Compilation error on file lib/monitor.ex ==
** (CompileError) lib/monitor.ex:13: a binary field without size is only allowed at the end of a binary pattern
    (stdlib) lists.erl:1337: :lists.foreach/2
    (stdlib) erl_eval.erl:669: :erl_eval.do_apply/6

Is there any solution for that?

like image 313
leifg Avatar asked Sep 08 '15 02:09

leifg


1 Answers

Check for match:

String.ends_with? filename, "_spec.exs"

Extract file:

file = String.trim_trailing filename, "_spec.exs"
like image 172
Sam Houston Avatar answered Oct 25 '22 00:10

Sam Houston