Is it possible to define a function which executes only if parameter x is not equal to ""

Is it possible to do something like this in Elixir?

  def build_query(query, "name", name != "", _conn) do
    Ecto.Query.where(query, [p], p.name == ^name)
  end
  def build_query(query, "name", name, _conn) when name != "" do
    Ecto.Query.where(query, [p], p.name == ^name)
  end
2 Likes

However, I would consider filtering out this kind of thing at a layer closer to the input and not worrying about it later on when building the query.

1 Like

You mean on the UI front-end? Not sending parameter name if it is empty?

That’s one option, or at the controller layer, or whatever bit of code first touches the params.

@benwilson512 … What is the Elixir/Phoenix way to filter away parameter if it is “”?

There is a scrub_params plug. Here’s a discussion about it and here are the docs. As far as I remember, it replaces empty strings ("" or " ") with nil.

2 Likes