Hi everyone.
Does anybody know if there is an idiomatic way of doing a pattern matching on a list of assertions
I am trying to do this.
assert (case git_short_commit do
"" -> true
<<_::8*7>> -> true
_ -> false
end)
Thank you.
Not sure if this is any better?
assert $git_short_commit == "" or match?(<<_::8*7>>, $git_short_commit)
1 Like
lud
3
I’m not sure it would be useful in this case, but there is the flunk
function:
(by the way, what is this “$”? Is it a typo?)
case stuff do
"" -> assert true
<<_::8*7>> -> assert true
_ -> flunk("the variable was not an empty string or a 7 byte binary")
end
4 Likes
It’s a PHP variable that made its way into Elixir!
1 Like
assert [
&match?("", &1),
&match?(<<...>>, &1)
]
|> Enum.map(fn check -> check.(value) end)
|> Enum.any?(& &1)
This maybe.
1 Like
Or switch the assert method around:
case value do
... -> :ok
... -> :ok
_ -> flunk "Invalid value"
end
3 Likes
you mean like @lud proposed up there?
Thank you, This is a beautiful approach.
1 Like
This one might be more intention-revealing:
blank? = (git_short_commit == "")
seven_bytes? = match?(<<_::8*7>>, git_short_commit)
assert blank? || seven_bytes?, "git short commits must be 7 bytes long (or blank), got: #{git_short_commit}"
2 Likes
I will just do:
assert valid_commit?(git_short_commit)
...
defp valid_commit?(""), do: true
defp valid_commit?(<<_::8*7>>), do: true
defp valid_commit?(_), do: false
2 Likes
The problem with these solutions is that as there are more clauses, it becomes really hard to read.