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 ?
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.