Taking Advantage of Mix Config

I've been experimenting with writing an elixir library that can make purchases using the Paypal API. Source here. While working on this lib, I needed a way configure it for different environments (test, dev, production). Coming from Ruby I'd typically reach for YAML and be on my marry way.

Meanwhile Jedi Master José felt a disturbance in the force and tweeted to the world about the dark path I was headed down.

Alright lets see what this elixir config stuff is all about!

When you create a new project with mix it creates this handy folder called config and a config.exs file. This file is well documented and uses Mix.Config check it out for more details!

Reading through the comments I opted to set it up so each environment could set it's own config. I promptly un-commented import_config "#{Mix.env}.exs" then created config/test.exs config/dev.exs and config/prod.exs.

To get started using the Paypal API I needed a couple things configed.

# config/dev.exs
config :ppt,  
user: "AeosmXJ1nZWwJgErHHhzxpOS0fH7Ki6qu4LVEotJA3al_bsZcnnYsvc1dDAi_71JYIdwkxeFHDu4sdEy"  
secret: "EDL8FGl7O6Xy-oIjdvcl4TRrx9EqKEkU_vKTi2qV3S95vfh1RB9gqiBJ6Uys-NuhSWCOn3FO84JFdpXy",  
currency: "USD"  

Don't worry those keys are only have access to a sandbox API.

Alright so we got some values setup in our config. How do we get access to them?! As simple as this: Application.get_env(:ppt, :user). This way you are sure to grab the right key for whatever environment you are running in, whether it be test, dev, prod or something else.

So how does this work when you're lib is imported into another mix application that also has its own environment configs?

I imported the paypal lib into another learning project of mine, a shopping cart powered by the phoenix framework.

Using the shopping carts environment config files I was able to override any of the keys from the imported paypal library! Super cool and super easy! From my understanding the way it works is as follows:

Projects config.exs -> App's Env.exs

If the key is unset in any of these files it moves on to the next one in the list. So in my case the priority of which value Application.get_env would return would be.

  1. shopping_cart's environment config file.
  2. ppt's config file

Elixir's built in way to handle configuration is very well thought out, and should be the convention of configuring your elixir libraries and applications!