Reputation: 2830
Simple one - how to truncate text of a blogpost on (let's say) 3rd paragraph? And tell it explicitly not render images?
I am using markdown btw. Can this be done in some 'elegant' way with simple code and no external gems in pure ruby?
If not, how to best implement it?
Upvotes: 0
Views: 335
Reputation: 4880
For truncating paragraphs something like the following should work:
def truncate_by_paragraph(text, num=3)
# since I'm not sure if the text will have \r, \n or both I'm swapping
# all \r characters for \n, then splitting at the newlines and removing
# any blank characters from the array
array = text.gsub("\r", "\n").split("\n").reject { |i| i == "" }
array.take(num).join("\n") + ".." # only 2 dots since sentence will already have 1
end
To remove images you can do the following:
def remove_images(text)
text.gsub(/<img([^>])+/, "")
end
Then you can do
truncate_by_paragraph(@text) # will return first 3 paragraphs
truncate_by_paragraph(@text, 5) # will return first 5 paragraphs
remove_images(truncate_by_paragraph(@text)) # 3 paragraphs + no images
Depending on the formatting you're after you might want to change the join
in the first method to join("\n\n")
to get double spacing.
Also if you really want ...
at the end of the text you might want to test whether the 3rd paragraph has a dot or not, or maybe it already has 3.
Upvotes: 4