Reputation: 4116
I have the following logic, if true I'm rendering a partial.
@taxon.tag.present? && @taxon.tag.include?('shirts') || @taxon.tag.present? && @taxon.tag.include?('dibs')
I'm trying have the following behaviour: if taxon.tag is present and includes shirts or dibs
render my partial.
I don't like that I'm repeating code so much.
I tried @taxon.tag.present? && %w(shirts dibs)include?(@taxon.canonical_tag)
didn't work because tag for shirts is: "shirts/url/url" it would work if it was "shirts"
what would be a quick way to refactor this?
Upvotes: 1
Views: 161
Reputation: 35004
One way to do this would be
( (@taxon.tag || []) & ["shirts", "dibs"] ).present?
This might be helpful.
Let me try to explain the solution:
# @taxon.tag looks like an enumerable, but it could also be nil as you check it with
# .present? So to be safe, we do the following
(@taxon.tag || [])
# will guarentee to return an enumerable
# The & does an intersection of two arrays
# [1,2,3] & [3,4,5] will return 3
(@taxon.tag || []) & ["shirts, "dibs"]
# will return the common value, so if shirts and dibs are empty, will return empty
( (@taxon.tag || []) & ["shirts, "dibs"] ).present?
# should do what you set out to do
Upvotes: 4