Â
 Â
Let’s handle file name extensions with Elixir, useful to validate the type of format of files that we would like to allow.
Step 1:
Let’s create a new Elixir project by going to the command line and typing the following in your desired directory:
$ mix new file_validator && cd file_validator
Step 2:
Open your test file test/file_validator_test.exs
, remove the autogenerated test and add the following test:
test "file validation should be false" do
file = "somefile.exe"
assert FileValidator.valid?(file) == false
end
test "file validation should be true" do
file = "somefile.png"
assert FileValidator.valid?(file) == true
end
Go to the command line and run the test mix test
Step 3:
Let’s make our test pass by opening our main project file lib/file_validator.ex
, remove the autogenerated hello world function and add the following:
@extension_whitelist ~w(.jpg .jpeg .gif .png .pdf)
def valid?(file) do
file_extension = get_ext(file)
@extension_whitelist
|> Enum.member?(file_extension)
end
defp get_ext(file) do
file
|> Path.extname()
|> String.downcase()
end
Get back to the command line and run the test mix test
now our test should pass with no failures.
Code Breakdown
@extension_whitelist ~w(.jpg .jpeg .gif .png .pdf)
The @
symbol means that is a module attribute, that can be used as a constant throughout our module.
The ~w sigil is used to generate lists of words(words are just regular strings). Inside the ~w sigil, words are separated by whitespace.
Path.extname(path)
Returns the extension of the last component of the path of a string.
Enum.member?(list, element)
Checks if an element exists within the list.
Conclusion
That’s a pretty simple and straightforward way to validate a file format, by getting the extension from the string with Path.extname(path)
and passing it to Enum.member?(list, element)
along with a whitelisted list of allowed file extensions. Thank you so much for your time, I really appreciate it.