How to improve function and remove extra from it's code

Hello, I want to try to improve my code, please see the below code :

def test() do
  with {:ok, %{acl: "admin", info: _info}} <- TrangellApiGateway.User.Login.user_acl_check(allreq),
            {:ok, ms} <- http_error_handeller(conn, Post.name(allreq), "created")  do
            conn
            |> put_status(201)
            |> json(%{message: ms})  
      else
            _ ->
               conn
               |> put_status(400)
               |> json(%{error: "Your request is invalid."}) 
      end
end

Please see the Post.name(allreq), I want to replace some Fun like `Post.other_name(allreq) insted of that, but I dont want to remove the other code of this function.

for exampel

The code concerned should be blow code :

fn 2

def test() do
  with {:ok, %{acl: "admin", info: _info}} <- TrangellApiGateway.User.Login.user_acl_check(allreq),
            {:ok, ms} <- http_error_handeller(conn, Post.other_name(allreq), "created")  do
            conn
            |> put_status(201)
            |> json(%{message: ms})  
      else
            _ ->
               conn
               |> put_status(400)
               |> json(%{error: "Your request is invalid."}) 
      end
end

I just edited Post.other_name(allreq), not anything else .

My friend told me that I could use action_fallback , but I don’t know how to use it in my code , if I can do this , My code will be 80% optimized

How do I do ?

ref :


https://hexdocs.pm/phoenix/Phoenix.Controller.html#action_fallback/1

Pseudo-Code as there are missing parameters in those functions, but it should convey the point. You could pass just the function name or the module and the function.

def test_1(), do: test(:name)
def test_2(), do: test(:other_name)

defp test(function_name) do
  with {:ok, %{acl: "admin", info: _info}} <- TrangellApiGateway.User.Login.user_acl_check(allreq),
            {:ok, ms} <- http_error_handeller(conn, apply(Post, function_name, [allreq]), "created")  do
            conn
            |> put_status(201)
            |> json(%{message: ms})  
      else
            _ ->
               conn
               |> put_status(400)
               |> json(%{error: "Your request is invalid."}) 
      end
end
1 Like

I think it is better to pass a lambda as an argument to test function. In this case, compiler can catch errors if function or module doesn’t exist.

def test_1(), do: test(&Post.name/1)
def test_2(), do: test(&Post.other_name/1)
1 Like