Ruby on Rails - 截断到特定的字符串

the*_*rod 4 ruby ruby-on-rails-3

澄清:帖子的创建者应该能够决定截断何时发生.

我在我的博客中使用以下辅助函数实现了类似[--- MORE ---]功能的Wordpress:

# application_helper.rb

def more_split(content)
split = content.split("[---MORE---]")
split.first
end

def remove_more_tag(content)
content.sub(“[---MORE---]", '')
end
Run Code Online (Sandbox Code Playgroud)

在索引视图中,帖子正文将显示(但没有)[--- MORE ---]标记的所有内容.

# index.html.erb
<%= raw more_split(post.rendered_body) %>
Run Code Online (Sandbox Code Playgroud)

在节目视图中,除了[--- MORE ---]标签外,还会显示帖子正文中的所有内容.

# show.html.erb
<%=raw remove_more_tag(@post.rendered_body) %>
Run Code Online (Sandbox Code Playgroud)

这个解决方案目前对我没有任何问题.由于我还是编程的初学者,我不断想知道是否有更优雅的方法来实现这一目标.

你会怎么做?

谢谢你的时间.


这是更新版本:

# index.html.erb
<%=raw truncate(post.rendered_body,  
                :length => 0, 
                :separator => '[---MORE---]', 
                :omission => link_to( "Continued...",post)) %>
Run Code Online (Sandbox Code Playgroud)

......并在展示视图中:

# show.html.erb
<%=raw (@post.rendered_body).gsub("[---MORE---]", '') %>
Run Code Online (Sandbox Code Playgroud)

dom*_*esz 8

我只使用截断,它具有您需要的所有选项.

truncate("And they found that many people were sleeping better.", :length => 25, :omission => '... (continued)')
# => "And they f... (continued)"
Run Code Online (Sandbox Code Playgroud)

更新

在看完评论后,挖掘了一些文档,似乎可以:separator完成工作.

来自doc:

Pass a :separator to truncate text at a natural break.
Run Code Online (Sandbox Code Playgroud)

对于referenece,请参阅文档

truncate(post.rendered_body, :separator => '[---MORE---]')
Run Code Online (Sandbox Code Playgroud)

在您必须使用的节目页面上 gsub

  • 如果用它定义长度,这似乎只能起作用:truncate(post.rendered_body,`:separator =>'[--- MORE ---]',:length => 0)` (2认同)