0

Good morning folks. In a model of mine, I created a method for displaying a row. The page wasn't working cause next and reify methods we're undefined , so I put a try on them. But the page doesn't load and is displaying this error on browser. "504 Gateway Time-out"

v = self.versions.first
 if v.present?
 while v.try(:reify).try(:reason).try(:name).blank? do
    v = v.try(:next)
  end
  v.reify.try(:reason).try(:name)
end

What do you recommend me to make this code much cleaner and to prevent it for long page loading again ?

Rails Coder.
  • 125
  • 1
  • 10

1 Answers1

3

Your code is effectively same as below after first iteration of loop, which is a infinite loop

while nil.try(:reify).try(:reason).try(:name).blank? # always true
   # ...
end

Your web server gives up while waiting for loop to terminate and hence reports - 504 - Gateway timeout to user/browser.


try allows you to invoke a method on a nil objects without throwing any exception - if object was nil or if method was not implemented, it will return nil.

So, lets say v was some object that did not implement reify method, then, v.try(:reify) will be nil

 v = "Ruby"
 v = v.try(:reify)
 #=> nil
 v = v.try(:next)
 #=> nil
 v.try(:reify).try(:reason).try(:name).blank?
 #=> true

Only solution for your problem is to ensure that your loop terminates.

Wand Maker
  • 18,476
  • 8
  • 53
  • 87
  • So it should look this now,right? 'v = self.versions.first if v.present? while v.try(:reify).try(:reason).try(:name).blank? do v = v.try(:next) end v.try(:reify).try(:reason).try(:name).blank? end' – Rails Coder. Feb 05 '16 at 12:01
  • @RailsCoder. Its hard to say without looking at exact value of `self.versions.first`. You will have to debug by inspecting its value. – Wand Maker Feb 05 '16 at 12:08