0

K... 这看起来很简单,但似乎不是标准化的。我只找了几个小时,但希望这里有人能指出我正确的方向。

因此, an 的实例Object具有描述。 Object has_many comments. 例如,如果用户在其中一个字段中发布 URL,例如http://www.foodnetwork.com/recipes/ree-drummond/tequila-lime-chicken-recipe/index.html 。当我输入这个时,我在下面看到了某种东西,知道将其转换为可点击的链接。我想更进一步。我希望看到相同的链接仅转换为主 url,但仍然是实际链接,a la foodnetwork

rails 可以在运行中做这样的事情吗?有这样的宝石吗?我应该着手制作上述的 link_bot gem 吗?

在一些正确方向的指示之后,我使用了一个辅助方法,因为在模型中播放不起作用。看法:

<% if object.comments.any? %>
  <% object.comments.each do |comment| %>
    <div class='comment block'>
      <div class='comment user'>
        <%= first_name(comment.user) %>
        <span class='comment time'><%= time_ago_in_words(comment.created_at) %> ago</span>
      </div>
      <div class='comment content'>&nbsp;&nbsp;
        &nbsp;&nbsp;<%= parse_links(comment.content) %>
      </div>
    </div>
  <% end %>
<% end %>

在助手中:

def parse_links(comment)
  auto_link(comment, html: {target: '_blank'}) do |text|
    URI.parse(text).host
  end
end

干杯!

4

1 回答 1

1

You should try the auto_link gem.

They give an example of playing around with the link text:

post_body = "Welcome to my new blog at http://www.myblog.com/.  Please e-mail me at me@email.com."
auto_link(post_body, :html => { :target => '_blank' }) do |text|
  truncate(text, 15)
end
# => "Welcome to my new blog at <a href=\"http://www.myblog.com/\" target=\"_blank\">http://www.m...</a>.

Update

Try this:

<%= auto_link(comment.content, html: {target: '_blank'}) do |text| %>
   # if URI.parse(text).host doesn't work try a regex:
   <%= text.match(/http:\/\/([^\/]*).*/)[1] %> # is there a better way to do this regex?
   # also try just <% instead of <%= if you get weird outputs.
<% end %>

If you get any errors add them to your question.

于 2013-05-03T01:01:27.103 回答