Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Grabbing the first paragraph from a text unit with RoR?

The title pretty much explains it. I'm writing a blog engine for myself with Ruby 1.9.3 and Rails 3.2.2 and I need to be able to grab the first paragraph from a post (which is stored as a text unit in the DB) to use as a post summary for the front page. What's the simplest way of doing this?

Google revealed very little on this issue; it doesn't seem like a common need.

like image 719
John Wells Avatar asked Dec 17 '22 01:12

John Wells


1 Answers

The answer becomes rather obvious once you start thinking what exactly defines "a paragraph" in your world.

If it is the first list of characters followd by two newline characters? Something like

str.split("\n\n", 2)[0]

could work.

If you have HTML and your paragraphs are defined by <p> tags, use nokogiri like

Nokogiri::HTML.parse(input_string).css('p').first.text

But agin, it all depends on how you define your paragraph. And stuff like this most often solves itself once you start thinking about what exactly you want to have, i.e. how to transform the input data to output data in an abstract way. The required algorithm comes naturally from these steps.

like image 66
Holger Just Avatar answered Dec 18 '22 15:12

Holger Just