Skip to content

Commit

Permalink
random_dom_id
Browse files Browse the repository at this point in the history
  • Loading branch information
mayel committed Nov 21, 2024
1 parent 99d532b commit 3f7d283
Show file tree
Hide file tree
Showing 2 changed files with 35 additions and 6 deletions.
4 changes: 2 additions & 2 deletions lib/modularity/extension_diff.ex
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ defmodule Bonfire.Common.Extensions.Diff do
"""
import Untangle
use Bonfire.Common.Localise
alias Bonfire.Common.Text

@doc """
Generates a diff between the specified reference or branch and the latest commit in the repository.
Expand Down Expand Up @@ -242,8 +243,7 @@ defmodule Bonfire.Common.Extensions.Diff do
end

def tmp_path(prefix) do
random_string = Base.encode16(:crypto.strong_rand_bytes(4))
Path.join([System.tmp_dir!(), prefix <> random_string])
Path.join([System.tmp_dir!(), prefix <> Text.unique_string()])
end

def root, do: Bonfire.Common.Config.get(:root_path)
Expand Down
37 changes: 33 additions & 4 deletions lib/text.ex
Original file line number Diff line number Diff line change
Expand Up @@ -96,7 +96,9 @@ defmodule Bonfire.Common.Text do
do: :binary.split(string, ["\r", "\n", "\r\n"], [:global])

@doc """
Generates a random string of a given length.
Generates a *random* string of a given length.
See also `unique_string/1` and `unique_integer/1`
## Examples
Expand All @@ -106,10 +108,37 @@ defmodule Bonfire.Common.Text do
> random_string()
#=> a string of length 10
"""
def random_string(length \\ 10) do
:crypto.strong_rand_bytes(length)
def random_string(str_length \\ 10) do
:crypto.strong_rand_bytes(str_length)
|> Base.url_encode64()
|> binary_part(0, length)
|> binary_part(0, str_length)
end

@doc """
Generates a *unique* random string.
"Unique" means that this function will not return the same string more than once on the current OTP runtime.
## Examples
iex> unique_string()
"""
def unique_string() do
unique_integer()
|> Integer.to_string(16)
end

@doc """
Generates a *unique* random integer.
"Unique" means that this function will not return the same integer more than once on the current OTP runtime.
## Examples
iex> unique_integer()
"""
def unique_integer() do
System.unique_integer([:positive])
end

@doc """
Expand Down

0 comments on commit 3f7d283

Please sign in to comment.