Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Iterate over object(s) if present, single or plural

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?

like image 590
brabertaser19 Avatar asked Dec 01 '22 02:12

brabertaser19


1 Answers

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.

like image 94
Billy Chan Avatar answered Dec 07 '22 01:12

Billy Chan