1

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?

xlembouras
  • 8,215
  • 4
  • 33
  • 42
neo
  • 4,078
  • 4
  • 25
  • 41

1 Answers1

4

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
Community
  • 1
  • 1
Bibek Shrestha
  • 32,848
  • 7
  • 31
  • 34
  • Defining a constant for the tags would help here. – tadman Nov 17 '14 at 21:44
  • amazing, ended up going with `@taxon.tag.present? && ['shirts', 'dibs'].present?` – neo Nov 17 '14 at 21:59
  • 1
    @neo That isn't going to do what you want, it's just checking if `@taxon.tag` is present, since the latter clause is always true. `&` is not the same as `&&`. – Chris Heald Nov 17 '14 at 22:38
  • 1
    Make sure that it isn't just always returning true if @taxon.tag is non-nil, because that's what the code in your comment will do. – Chris Heald Nov 18 '14 at 05:04