acrolink
How to check for a condition inside a pipe chain?
Inside a pipe chain, how to execute one pipe line / exclude it based on say is_list(variable)? i.e. execute pipe line 5 only if variable is a list. Is that possible?
Marked As Solved
rossta
It might be possible to extract a function where you can pattern match and compose the query. Here’s what it could look like for the expires policy (actual code may depend on where your functions and usage are located):
# Policy module
def with_expiry(page, nil) do
expires_params = "01-01-1970" |> Timex.parse!("%d-%m-%Y", :strftime) |> Ecto.DateTime.cast!
page |> where([p, c], p.expires >= ^expires_params)
end
def with_expiry(page, expires_params) do
page |> where([p, c], p.expires >= ^expires_params)
end
#...
page =
Policy
|> join(:left, [p], c in Client, p.client_id == c.id)
|> where([p, c], c.user_id == ^conn.assigns.current_user.id)
|> Policy.with_expiry(params["policy"]["expires"])
# ...
Also Liked
acrolink
@rossta, @vidalraphael, @kelvinst
Thank you very much.. I have learned new things here today.. I am happy that I have found my way back to this forum after some bad bi yearly banning experiences at holy stackoverflow (latest only because I asked a duplicate question)..
OvermindDL1
I’m often lazy and just put a case between things… >.>
value
|> something(42)
|> something_else()
|> case do
page where limit_size == nil -> page
page -> page |> limit(size)
end
|> some_more_things()
...
Also you really need to use code tags instead of quotes for bodies of code, you do it like:
```elixir
Code goes here like 2+2
```
Makes:
Code goes here like 2+2
wolf4earth
As a possible alternative to writing a full fledged maybe_* function, you can also consider to use a general purpose maybe_if/3 function. I’ve done that in the past when I needed to chain multiple optional steps.
initial_data
|> first_transformation()
|> maybe_if(should_apply_step2, &second_transformation/1)
|> maybe_if(should_apply_step3, &third_transformation_with_params(&1, my_param))
|> another_one()
where maybe_if is defined like this:
def maybe_if(data, true, action)
when is_function(action, 1),
do: apply(action, data)
def maybe_if(data, false, _action), do: data
Popular in Questions
Other popular topics
Categories:
Sub Categories:
Forums
Popular Tags
- #ecto
- #liveview
- #troubleshooting
- #learning-elixir
- #deployment
- #library
- #erlang
- #testing
- #genserver
- #mix
- #absinthe
- #remote-other
- #otp
- #plug
- #how-to-question
- #macros
- #postgres
- #channels
- #elixirconf
- #exunit
- #discussion
- #code-sync
- #javascript
- #podcasts
- #onsite
- #dialyzer
- #docker
- #authentication
- #umbrella
- #full-time-contract
- #podcasts-by-brainlid
- #ecto-query
- #elixir-ls
- #phoenix_html
- #iex
- #blog-post
- #graphql
- #genstage
- #ai
- #websockets
- #supervisor
- #advent-of-code
- #elixirconf-us
- #distillery
- #processes
- #forms
- #api
- #metaprogramming
- #security
- #performance








