Let's say that i have object my_obj
and i get this object from database, with some more calculation, it doesn't matter...
and then i need to iterate via such object, like:
my_obj.each do |m|
some_method(m.id)
end
this code is not good, becouse if my_obj is nil, i will get error like:
undefined method `each' for nil:NilClass
so i decide to write:
if my_obj.present?
my_obj.each do |m|
some_method(m.id)
end
end
but i think that there is one more way of doing this, without writting everywhere if construction.
so how could i iterate via object, only if it is not null?
I found the code a bit anti-pattern for normal OOP principle "Tell, Don't ask". I tried the question in console and found your worry unnecessary.
No matter what the result is, blank Array or blank ActiveRecord::Relation object, each
all works and return a blank array []
.
Article.count
# => 0
articles = Article.all # Return array in Rails 3
articles.each { |a| puts a.title }
# => []
articles = Article.scoped # Return ActiveRecord::Relation object in Rails 3
articles.each { |a| puts a.title }
# => []
I would suggest you to review the method and returned result of your query. If your query returns unusual things, make sure it returns at least a blank Array. Then you don't need to consider too much.
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