so i have a code :
whitelisted_params =
params
|> Map.take(
~w(id ph_id name address)
)
|> Enum.map(fn {k, v} -> {String.to_atom(k), String.replace(v, ~r/[^\w\s\-]/, "")} end)
i’m trying to convert String.replace(v, ~r/[^\w\s\-]/, "")
to integer if key is id or ph_id
NobbZ
2
The if/2
would work as everywhere else as well:
fn {k, v} ->
k = String.to_atom(k)
v = String.replace(v, ~r/[^\w\s\-]/, "")}
v = if k in [:id, :ph_id] do
String.to_integer(v)
else
v
end
{k, v}
end
For a bit more readability I’d also make the chain longer and use pattern matching, like this:
params
|> Map.take(~w(id ph_id name address))
|> Enum.map(fn {k, v} -> {String.to_atom(k), String.replace(v, ~r/[^\w\s\-]/, "")} end)
|> Enum.map(fn
{k, v} when k in [:id, :ph_id] ->
{k, String.to_integer(v)}
tuple ->
tuple
end)
3 Likes