Search code examples
fileparsingelixirelixir-mix

How to read config files on elixir mix project


I am creating an elixir project to search for patterns in files. I want to store those patterns a config files to allow for easy changes in the app. My first idea is storing those files as exs files in the config folder in the mix project. So, the questions are:

  1. Is there any easy way to store the config in the files a a keyword list?
  2. How would I load it in the app?

I see there are modules like File to read the file, but is there no standard way to parse keyword lists in elixir? I was thinking something similar as the yml files in Rails.


Solution

  • You can read keyword lists stored in a *.exs file, using Mix.Config.read(path). For writing Elixir terms to a *.exs file, you can use Inspect.Algebra.to_doc(%Inspect.Opts{pretty: true}) and write the resulting string content to a file using File.write. It's not as well formatted as if you did it by hand, but it's definitely still readable.

    If you don't mind using Erlang terms, you can read and write those easily using :file.consult(path) and :file.write_file(:io_lib.fwrite('~p.\n', [config]), path) respectively.