I've had to use begin rescue way to many times, and I want to refactor but I can't create a method where I pass a parameter that uses the .parent method.
This is because .parent is the method that raises the error, but that is the only thing that is changing and I don't know how to write the code without calling the method
I do want to get the parent name, but if there is no parent that is why I get the error. So i essentially need it to return a empty string when there is no parent, but I don't know how to recursively add a .parent.:
def check_parent_name(object)
if ['body','html', 'head', 'document'].include?(object.parent.name)
''
else
object.parent.content
end
end
begin
parent_content = check_parent_name(img.parent)
rescue => e
parent_content = ''
end
begin
parent_parent_content = check_parent_name(img.parent.parent)
rescue => e
parent_parent_content = ''
end
begin
parent_parent_parent_content = check_parent_name(img.parent.parent.parent)
rescue => e
parent_parent_parent_content = ''
end
begin
parent_parent_parent_parent_content = check_parent_name(img.parent.parent.parent.parent)
rescue => e
parent_parent_parent_parent_content = ''
end
begin
parent_parent_parent_parent_parent_content = check_parent_name(img.parent.parent.parent.parent.parent)
rescue => e
parent_parent_parent_parent_parent_content = ''
end
A very simple way is to use directly rescue
inside your statement:
parent_content = check_parent_name(img.parent) rescue ""
But this is not the way you should code.
Like DaveNewton said, we need to know what use of this code you want, and we could help you to find a better, cleaner and more flexible way to implement the feature!
It seems that you have a structure as Tree (parent-children) between your records, am I wrong?
A recursive method (= calling itself) is propably what you want here, something like:
def your_method(img)
return "" unless img.present?
if img.try(:parent).present?
your_method(img.parent)
else
return check_parent_name(img)
end
end
But I don't know for sure it is what you want...