I have the following code that parses HTML text and trims (or strips) the paragraphs that are empty. It’s similar to .strip on a String object.
doc = Nokogiri::HTML::DocumentFragment.parse(html)
# repetition that I want to collapse
doc.css('p').each do |p|
if all_children_are_blank?(p)
p.remove
else
break
end
end
# repetition that I want to collapse
doc.css('p').reverse_each do |p|
if all_children_are_blank?(p)
p.remove
else
break
end
end
doc.to_s.strip
Is there a more elegant way to prevent code that I’ve labelled with comments to be duplicated and adhere to principles of code-reuse?
Here is what I’ve come up with but I’m not happy with it yet and wanted to see if there is something better:
doc = Nokogiri::HTML::DocumentFragment.parse(html)
doc.css('p').each do |p|
if stop(p) then break end
end
doc.css('p').reverse_each do |p|
if stop(p) then break end
end
doc.to_s.strip
def self.stop(p)
if all_children_are_blank?(p)
p.remove
false
else
true
end
end
If I understand what you’re looking for, you would like a simpler way to iterate over the elements you’re looking at, in order to remove blank
pelements.Here is a straightforward way to collapse what you’ve written, without doing a whole lot different:
I have not tested this out, so you might need to tweak it a little. If this were production code, I would probably decompose it into one or more method calls in order to keep things clear.