Define numbers and multi-level variable in config with phoenix

I have managed to add config variables using this syntax

config :a_c, :custom,
  c_p: 20

and for nested conf I have managed to add something like this:

config :a_c, :custom,
  s: [
    static: [
      u: "http://localhost:90",
      d: [
          id: "006",
          url: "som_url",
          is_a: true,
          c_p: 15
      ]
    ]
  ]

but what I really want is to use a number instead of static like this:

config :a_c, :custom,
  s: [
    007: [
      u: "http://localhost:90",
      d: [
          id: "006",
          url: "som_url",
          is_a: true,
          c_p: 15
      ]
    ]
  ]

and I want to define more than one object inside d like this:

config :a_c, :custom,
  s: [
    007: [
      u: "http://localhost:90",
      d: [
         {
          id: "006",
          url: "som_url",
          is_a: true,
          c_p: 100
        },
       {
          id: "009",
          url: "som_url2",
          is_a: true,
          c_p: 155
        },

      ]
    ]
  ]

and get it like this:

 @s Application.get_env(:a_c,:custom)[:s]  
 c_p= @s[:007][:d][0][:c_p]

instead of

 @s Application.get_env(:a_c,:custom)[:s]  
 c_p= @s[:static][:d][:c_p]

Then use maps instead of keyword lists.

# This is a keyword list:
a_keyword_list = [a: 123, b: "something"]

# Which is just syntactic sugar for a list of {atom, term} tuples:
[{:a, 123}, {:b, "something"}] == a_keyword_list
#=> true

# This instead is a map:
a_map = %{a: 123, b: "something"}

# A map can use anything as keys, not only atoms:
also_a_map = %{"string key" => 123, 321 => "something"}

Keyword lists and maps have other differences with regards to performance and support for duplicated keys, but both of them implement the Access behavior, so you can use map[key] or keyword_list[key].

Both keyword lists and maps can have anything as values, including lists. The reason why it’s not working in your case, is that you are using the wrong syntax:

  • {a, b, c} is a tuple
  • [a, b, c] is a list
  • [key: value, other_key: other_value] is a keyword list
  • In some special cases the square brackets for keyword lists can be omitted, for example when the keyword list is the last argument of a function call: some_function(key: value, other_key: other_value).
  • %{key => value, other_key => other_value} is a map
  • Maps with atom keys can also be written as %{key: value}, which is equivalent to %{:key => value}

Therefore, if you want a list of maps, you need to use something like: [%{id: 1, foo: "bar"}, %{id: 2, bar: "baz"}].

You can read more about them in the official documentation. Also, if you did not do that yet, go through the Getting Started guide on the Elixir language website: it is very informative and will clarify a lot of concepts, including this one.

1 Like