Rails 谁知道 Rails 的显示部分内容的插件

zhaoguobin · December 26, 2011 · Last by whocare replied at February 04, 2012 · 4445 hits

本人想把搜索结果显示出来,遇到一个问题,就是内容太长,有没有一个只显示部分内容的插件。

怎样只显示搜到关键字的那一小块内容?

thinking-sphinx 默认就带这个功能的

#1 楼 @huacnlee 能不能给个介绍的网址,看了半天文档没找着。

顺路收藏。。。

用 CSS 实现也可以,如果不介意结果页面太大

http://mattsnider.com/css/css-string-truncation-with-ellipsis/

地球人不是都用 Rails build-in 的 truncate 方法麼? <%= (truncate(strip_tags(post.body), :length => 60, :omission => '...')).html_safe %>

社区中似乎没有一个类似名为 act_as_teaser 的 gem,可以使用宏语句为:text 类型的字段,比如 content 字段提供一个 content_teaser 的自动截断版本,并且也允许手工 teaser,,, 是我没找到,,还是不存在? 或许应该花点时间自己写一个 :)

#7 楼 @Victor 你误解意思了,搜索的时候,如果文章很长,而搜索摘要只需要 200 字,这个时候 200 字应该显示有关键词匹配到的部分,而不是“字符串截取”

#9 楼 @huacnlee 只注意 lz 的第一句話,沒注意看第二句。:P

顺手写了一个 act_as_teaser 的 gem,感觉不是很好,主要是摘要与主体之间的同步问题,晾出来请大家指教如何改进,,,

使用方法: 在 model 中,

class Article < ActiveRecord::Base
  # 假设存在:content和:teaser两数据库列,以下DSL指定使用:teaser字段保存:content的摘要,当:content更新时,自动截取生成:teaser
  act_as_teaser :content,:as=>:teaser 

end

模块源码

module ActAsTeaser
  extend ActiveSupport::Concern

  included do
    include ActionView::Helpers::SanitizeHelper 
    include ActionView::Helpers::TextHelper
  end

  module ClassMethods
    def act_as_teaser body, opts={}
      teaser = opts[:as] || 'teaser'
      length = opts[:length] || 100
      self.class_eval %(
        protected
        def filter_teaser_#{body}          
          if changed.include?("#{body}") && !changed.include?("#{teaser}")
            self.#{teaser} = truncate(strip_tags(self["#{body}"]),:length=>#{length})
          end    
        end              
      )
      self.before_save "filter_teaser_#{body}".to_sym
    end
  end

end

ActiveRecord::Base.send :include,ActAsTeaser

You need to Sign in before reply, if you don't have an account, please Sign up first.