How to generate a random url safe string with Elixir

后端 未结 3 1973
野的像风
野的像风 2021-02-05 00:47

I need to be able to generate random url safe strings so I could use those in links (like in an activation link sent to a user\'s email), so how can I generate it? Is there a wa

3条回答
  •  面向向阳花
    2021-02-05 01:47

    You can easily define a module to do this. In this example, @chars determines what characters appear in your generated strings.

    defmodule StringGenerator do
      @chars "ABCDEFGHIJKLMNOPQRSTUVWXYZ" |> String.split("")
    
      def string_of_length(length) do
        Enum.reduce((1..length), [], fn (_i, acc) ->
          [Enum.random(@chars) | acc]
        end) |> Enum.join("")
      end
    end
    
    StringGenerator.string_of_length(3) # => "YCZ"
    

提交回复
热议问题