I'm trying to write a little snippet for my Rails app that checks if any tags are present for an object.
I have the following code:
def any_tags_present?(obj,*tags)
tags ||= %w(person city country other)
tags.any? { |tag| obj.send("#{tag}_list").present? }
end
running tags.any? { |tag| obj.send("#{tag}_list").present? } will return true if I call it directly:
obj = Article.first
tags ||= %w(person city country other)
tags.any? { |tag| obj.send("#{tag}_list").present? }
=> true
but if I call it with any_tags_present?(Article.first) I get false:
obj = Article.first
any_tags_present?(obj)
=> false
What gives?
You can something like
def any_tags_present?(obj, tags=nil)
tags ||= %w(person city country other)
tags.any? { |tag| obj.send("#{tag}_list").present? }
end
obj = Article.first
any_tags_present?(obj)
So if you don't pass tags then it gets initialized by %w(person city country other)
The problem is the line tags ||= %w(person city country other). It doesn't get (re)assigned, because tags will be an empty Array ([]) and not nil. Possible solutions are just taking an default argument of nil and passing in an Array or checking if tags is empty.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With