option to strip links from excerpts

This commit is contained in:
Sam 2013-04-30 13:25:55 +10:00
parent 94a578e4b2
commit b25a5a20bb
5 changed files with 29 additions and 18 deletions

View file

@ -221,14 +221,14 @@ class Post < ActiveRecord::Base
user_id: user_id).first.try(:user)
end
def self.excerpt(cooked, maxlength = nil)
def self.excerpt(cooked, maxlength = nil, options = {})
maxlength ||= SiteSetting.post_excerpt_maxlength
PrettyText.excerpt(cooked, maxlength)
PrettyText.excerpt(cooked, maxlength, options)
end
# Strip out most of the markup
def excerpt(maxlength = nil)
Post.excerpt(cooked, maxlength)
def excerpt(maxlength = nil, options = {})
Post.excerpt(cooked, maxlength, options)
end
# What we use to cook posts

View file

@ -60,7 +60,7 @@ class TopicListItemSerializer < ListableTopicSerializer
end
def excerpt
object.posts.first.try(:excerpt,200) || nil
object.posts.first.try(:excerpt,220, strip_links: true) || nil
end
end

View file

@ -56,7 +56,7 @@ class Autospec::Runner
Signal.trap("SIGINT") {stop_spork; exit }
puts "Forced polling (slower) - inotify does not work on network filesystems, use local filesystem to avoid" if force_polling
Thread.start do
Listen.to('.', force_polling: force_polling, filter: /^app|^spec|^lib/, relative_paths: true) do |modified, added, removed|
process_change([modified, added].flatten.compact)

View file

@ -239,14 +239,16 @@ module PrettyText
attr_reader :excerpt
def initialize(length)
def initialize(length,options)
@length = length
@excerpt = ""
@current_length = 0
@strip_links = options[:strip_links] == true
end
def self.get_excerpt(html, length)
me = self.new(length)
def self.get_excerpt(html, length, options)
me = self.new(length,options)
parser = Nokogiri::HTML::SAX::Parser.new(me)
begin
copy = "<div>"
@ -271,11 +273,13 @@ module PrettyText
characters("[image]")
end
when "a"
c = "<a "
c << attributes.map{|k,v| "#{k}='#{v}'"}.join(' ')
c << ">"
characters(c, false, false, false)
@in_a = true
unless @strip_links
c = "<a "
c << attributes.map{|k,v| "#{k}='#{v}'"}.join(' ')
c << ">"
characters(c, false, false, false)
@in_a = true
end
when "aside"
@in_quote = true
end
@ -284,8 +288,10 @@ module PrettyText
def end_element(name)
case name
when "a"
characters("</a>",false, false, false)
@in_a = false
unless @strip_links
characters("</a>",false, false, false)
@in_a = false
end
when "p", "br"
characters(" ")
when "aside"
@ -307,8 +313,8 @@ module PrettyText
end
end
def self.excerpt(html, length)
ExcerptParser.get_excerpt(html, length)
def self.excerpt(html, max_length, options={})
ExcerptParser.get_excerpt(html, max_length, options)
end
end

View file

@ -104,6 +104,11 @@ test
end
describe "Excerpt" do
it "should have an option to strip links" do
PrettyText.excerpt("<a href='http://cnn.com'>cnn</a>",100, strip_links: true).should == "cnn"
end
it "should preserve links" do
PrettyText.excerpt("<a href='http://cnn.com'>cnn</a>",100).should == "<a href='http://cnn.com'>cnn</a>"
end