Let’s handle file name extensions with Elixir, useful to validate the type of format of files that we would like to allow.
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
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
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.
@extension_whitelist ~w(.jpg .jpeg .gif .png .pdf)
@ 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.
Returns the extension of the last component of the path of a string.
Checks if an element exists within the list.
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.