【问题标题】:Ruby / Rails - Generate hyperlinks from words/phrases at render time?Ruby / Rails - 在渲染时从单词/短语生成超链接?
【发布时间】:2013-07-09 01:51:18
【问题描述】:

我已经搜索了很多答案,但我一直在寻找有关如何将纯文本链接变成可点击的超链接或从文本中去除超链接的文章。这两者都不是。

我希望能够在运行时解析出单词/短语并根据一些后端逻辑/数据从它们创建超链接。例如,用户个人资料可能有一个“关于我”部分,如下所示:

I went to xyz university and like basketball & football.

我想要一些可以创建超链接的功能:

  • “xyz 大学”文本链接到 school_path(“xyz 大学”)
  • "basketball" 文本链接到 sport_path("basketball") 和
  • “football”文本链接到 sport_path("football")

用户可以随时使用不同的运动、音乐等更改她/他的个人资料,我希望能够解决这个问题。如果我指定链接的单词/短语列表中不存在该单词或短语,则不会发生任何事情。

是否有某个术语我应该在谷歌上搜索,一些隐藏的 Ruby 类可以做到这一点,或者我找不到的宝石?

感谢您提供的任何帮助!

凯尔

【问题讨论】:

    标签: ruby-on-rails ruby hyperlink html-parsing ruby-on-rails-4


    【解决方案1】:

    我首先想到的是您谈论机器学习的主题,特别是关键字匹配。

    http://www.quora.com/What-are-good-tools-to-extract-key-words-and-or-topics-tags-from-a-random-paragraph-of-text

    我不确定最好的方法,但我的出发点可能是进行某种类型的 postgres 关键字搜索,该关键字搜索具有大量索引并包含为您提供路线的属性。您必须构建某种类型的键、值查找,并且您可能必须自己开始构建字典,因为我不确定您将如何根据单词获取主观信息。

    【讨论】:

      【解决方案2】:

      8一种方法...其他人可能会提出一些改进...

      创建一个名为 Substitutions 的模型和表,其中包含以下字段:phrase、hyperlink、phrase_length(保存前计算phrase_length)...

      # look for substitions in descending phrase length order
      # so that "Columbus University" is substituted instead of "Columbus" (the city)
      # replace matched phrase with a temporary eyecatcher storing substitution id
      # we do this so that other matches of smaller strings will disregard 
      # already matched text
      
      Substitution.order("phrase_length DESC").each do |subst| 
        paragraph.sub!( subst.phrase, "{subbing#{subst.id.to_s.rjust(8, '0')}}" )
      end
      
      # now replace eyecatchers with hyperlink string
      
      pointer = paragraph.index '{subbing' 
      while pointer 
        subst = Substitution.find(paragraph[pointer+9, 8].to_i)
        paragraph.sub!( "{subbing#{subst.id.to_s.rjust(8, '0')}}", subst.hyperlink )
        pointer = paragraph.index '{subbing' # continue while eyecatchers still present
      end
      

      【讨论】:

        猜你喜欢
        • 2011-08-30
        • 1970-01-01
        • 2019-05-25
        • 2018-03-27
        • 1970-01-01
        • 2014-11-09
        • 1970-01-01
        • 2011-01-20
        • 1970-01-01
        相关资源
        最近更新 更多