Skip to content

Instantly share code, notes, and snippets.

@joshleecreates
Created February 8, 2017 17:13
Show Gist options
  • Save joshleecreates/139066ecbbc2f4a9660f874827436711 to your computer and use it in GitHub Desktop.
Save joshleecreates/139066ecbbc2f4a9660f874827436711 to your computer and use it in GitHub Desktop.
def process_url(url) do
defaults = %{
thing: "thing1value"
}
uri = URI.parse(url)
params = URI.decode_query(uri.query, defaults) |> URI.encode_query
URI.merge(@base_url, uri.path <> "?" <> params) |> to_string
end
@doomspork
Copy link

doomspork commented Feb 8, 2017

@joshleecreates it is preferred to start pipes with a bare value, see: https://github.com/christopheradams/elixir_style_guide#bare-variables

Couple different takes on this:

@default_params %{thing: "thing1value"}

def process_url(url, params \\ @default_params) do
    %{query: query, path: path} = URI.parse(url)

    params = 
      query
      |> URI.decode_query(params) 
      |> URI.encode_query

    @base_url
    |> URI.merge(path <> "?" <> params) 
    |> to_string
end
@default_params %{thing: "thing1value"}

def process_url(url, params \\ @default_params) do
  uri
  |> URI.parse
  |> prepare_query(params)
  |> update_uri 
end

defp prepare_query(%{query: query, path: path} = uri, params) do
  query =
    query
    |> URI.decode_query(params) 
    |> URI.encode_query

  {path, query}
end

defp update_uri({path, query}) do
  fragment = path <> "?" <> query

  @base_url
  |> URI.merge(fragment)
  |> to_string
end

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment