开发者

Parse text to match db records and and transform them into links (Rails 3)

I'm looking for a way to parse a text to turn into links the entities of my web app contained within the text. To make it clear, let'开发者_StackOverflow社区s take this text as example:

Stoner rock and stoner metal are two related sub-genres of hard rock and heavy metal respectively, both combining elements of psychedelic rock, blues-rock, traditional heavy metal and doom metal. The genre emerged during the early 1990s and was pioneered foremost by the Californian bands Kyuss and Sleep.

I'd like to link all the genres, bands and albums that appear on the text (and exist as entities on my web app), like this:

<a href="/genre/1">Stoner rock</a> and stoner metal are two related sub-genres of hard rock and <a href="/genre/2">heavy metal</a> respectively, both combining elements of psychedelic rock, blues-rock, traditional <a href="/genre/2">heavy metal</a> and <a href="/genre/4">doom metal</a>. The genre emerged during the early 1990s and was pioneered foremost by the Californian bands <a href="/band/1">Kyuss</a> and <a href="/band/2">Sleep</a>.

I've thought different alternatives, such as:

  1. Storing rails code in the database which would output the links (Ugly and insecure),
  2. Do a full search on the database before inserting the text and

    a. Find and transform all my entities into links before saving or

    b. Store the entities ids on a separated column, place anchor tags and then on the view, combine each entity id with its anchor tag

I'm not really happy with any of the alternatives, I think should be a smarter way to handle this. Can you suggest a better approach? I'm using Ruby On Rails 3.


Pseudo-Codes:

Keywords.find_each do |keyword|
  text.gsub!(keyword, link_to keyword, some_path_for(keyword))
end

Depending on how many keywords you have, this task may be quite CPU intensive. Consider storing the text to DB first and have a background worker (like Resque or Delayed::Job) process each test.

Show the original (unlinked) text until it has been processed. I would suggest using two different table fields for the unlinked and linked texts.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜