Created
August 6, 2016 18:13
-
-
Save desmondhume/0fcb73bf6b7f4d9ed267d1c99c96471d to your computer and use it in GitHub Desktop.
Convert elixir map to query string
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
defmodule URL do | |
def to_query(input, namespace) do | |
Enum.map(input, fn({key, value}) -> parse("#{namespace}[#{key}]",value)end) | |
|> Enum.join("&") | |
end | |
def to_query(input) do | |
Enum.map(input, fn({key, value}) -> parse(key,value) end) | |
|> Enum.join("&") | |
end | |
def parse(key, value) when is_map(value) do | |
to_query(value, key) | |
end | |
def parse(key, value) do: | |
"#{key}=#{value}" | |
end | |
end |
I think https://hexdocs.pm/elixir/URI.html#encode_query/1 would be the first thing to try
Convert Query String Parameters into a Map of Key/Value Pairs:
iex(29)> String.split("from=ME&to=YOU&to_index=THERE&proof=PROVEN", ~r/&|=/) |> Enum.chunk(2) |> Map.new(fn [k, v] -> {k, v} end)
%{"from" => "ME", "proof" => "PROVEN", "to" => "YOU", "to_index" => "THERE"}
https://gist.github.com/ltfschoen/a52109ea5a9e020fa4abcaacbc43e8af
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Came here looking for a more elegant solution to what I felt wasn't very 'functional'.
The
to_query
function is especially neat! Thanks for the inspiration.