Concatenate link_to with pipe

I want to combine several links with a pipe. But all links are surrounded by if-statement.

Example:

- if condition1 = link_to link1 - if condition2 = link_to link2 - if condition3 = link_to link3 

If conditions 1 and 2 are true, the result should be

 link1 | link2 

Any clues on how to do this?

0
source share
1 answer

I would use smth for this purpose:

 = [[l1, c1], [l2, c2], [l3, c3]].map{ |l, c| link_to(l) if c }.compact.join('|') 

or

 = [(link_to(l1) if c1),(link_to(l2) if c2),(link_to(l3) if c3)].compact.join('|') 

The latter is a bit awkward, but it's a matter of taste. Both are perfect for filtering out unnecessary links and combining the rest with | .

Although, if your conditions are nontrivial, and you have quite a lot of them, it would be better to move this logic outside the view to the controller or some assistant (depending on the situation).

And if you have a general method of checking whether to show the link or not, say, show?(link) helper, then everything gets a little better, and you can do it like this:

 = [l1, l2, l3, l4].map{ |l| link_to(l) if show?(l) }.compact.join('|') 

or so:

 = [l1, l2, l3, l4].select{ |l| show?(l) }.map{ |l| link_to(l) }.join('|') 
0
source

Source: https://habr.com/ru/post/1433812/


All Articles