diff --git a/lib/ex_junk.ex b/lib/ex_junk.ex index 31ecbff..f2b7a47 100644 --- a/lib/ex_junk.ex +++ b/lib/ex_junk.ex @@ -35,11 +35,14 @@ defmodule Junk do junk_for_type(junk_type, merged_opts) end + defp junk_for_type(:"Elixir.String", %{prefix: nil} = opts), do: random_string(opts) + defp junk_for_type(:"Elixir.String", %{prefix: ""} = opts), do: random_string(opts) defp junk_for_type(:"Elixir.String", opts) do - string = random_bytes(opts) - |> Base.url_encode64 - opts.prefix <> "-" <> string + opts + |> random_string + |> String.replace_prefix("", opts.prefix <> "-") end + defp junk_for_type(:"Elixir.Integer", opts) do min = :math.pow(10, opts.size-1) |> trunc max = :math.pow(10, opts.size)-1 |> trunc @@ -49,4 +52,8 @@ defmodule Junk do defp random_bytes(%{rand_mod: rand_mod, byte_size: b_size}) do rand_mod.random_bytes.(b_size) end + + defp random_string(opts) do + opts |> random_bytes |> Base.url_encode64 + end end diff --git a/test/ex_junk_test.exs b/test/ex_junk_test.exs index ce863aa..6a048bc 100644 --- a/test/ex_junk_test.exs +++ b/test/ex_junk_test.exs @@ -28,6 +28,14 @@ defmodule JunkTest do assert String.starts_with?(output, "prefix-") end + test "String doesn't start with dash if prefix empty" do + output_with_blank_prefix = Junk.junk(String) + output_with_nil_prefix = Junk.junk(String, prefix: nil) + + refute String.starts_with?(output_with_blank_prefix, "-") + refute String.starts_with?(output_with_nil_prefix, "-") + end + test "returns unique Integers" do assert Junk.junk(Integer) |> is_integer == true assert Junk.junk(Integer) != Junk.junk(Integer)