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

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

我在我的博客中使用以下辅助函数实现了类似[— 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

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

# index.html.erb
<%= raw more_split(post.rendered_body) %>

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

# show.html.erb
<%=raw remove_more_tag(@post.rendered_body) %>

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

你会怎么做?

谢谢你的时间.

这是更新版本:

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

……并在展示视图中:

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

解决方法

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

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

更新

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

来自doc:

Pass a :separator to truncate text at a natural break.

对于referenece,请参阅docs

truncate(post.rendered_body,:separator => '[---MORE---]')

显示页面上,您必须使用gsub

相关文章

validates:conclusion,:presence=>true,:inclusion=>{...
一、redis集群搭建redis3.0以前,提供了Sentinel工具来监控各...
分享一下我老师大神的人工智能教程。零基础!通俗易懂!风趣...
上一篇博文 ruby传参之引用类型 里边定义了一个方法名 mo...
一编程与编程语言 什么是编程语言? 能够被计算机所识别的表...
Ruby类和对象Ruby是一种完美的面向对象编程语言。面向对象编...