mirror of
https://github.com/rails/rails.git
synced 2022-11-09 12:12:34 -05:00
skip extra work if no text or phrase was provided
This commit is contained in:
parent
dda81cb177
commit
ca59ec354e
1 changed files with 11 additions and 12 deletions
|
@ -134,6 +134,8 @@ module ActionView
|
|||
# excerpt('This is an example', 'an', 5) # => ...s is an exam...
|
||||
# excerpt('This is also an example', 'an', 8, '<chop> ') # => <chop> is also an example
|
||||
def excerpt(text, phrase, *args)
|
||||
return unless text && phrase
|
||||
|
||||
options = args.extract_options!
|
||||
unless args.empty?
|
||||
options[:radius] = args[0] || 100
|
||||
|
@ -141,20 +143,17 @@ module ActionView
|
|||
end
|
||||
options.reverse_merge!(:radius => 100, :omission => "...")
|
||||
|
||||
if text && phrase
|
||||
phrase = Regexp.escape(phrase)
|
||||
phrase = Regexp.escape(phrase)
|
||||
if found_pos = text.mb_chars =~ /(#{phrase})/i
|
||||
start_pos = [ found_pos - options[:radius], 0 ].max
|
||||
end_pos = [ [ found_pos + phrase.mb_chars.length + options[:radius] - 1, 0].max, text.mb_chars.length ].min
|
||||
|
||||
if found_pos = text.mb_chars =~ /(#{phrase})/i
|
||||
start_pos = [ found_pos - options[:radius], 0 ].max
|
||||
end_pos = [ [ found_pos + phrase.mb_chars.length + options[:radius] - 1, 0].max, text.mb_chars.length ].min
|
||||
prefix = start_pos > 0 ? options[:omission] : ""
|
||||
postfix = end_pos < text.mb_chars.length - 1 ? options[:omission] : ""
|
||||
|
||||
prefix = start_pos > 0 ? options[:omission] : ""
|
||||
postfix = end_pos < text.mb_chars.length - 1 ? options[:omission] : ""
|
||||
|
||||
prefix + text.mb_chars[start_pos..end_pos].strip + postfix
|
||||
else
|
||||
nil
|
||||
end
|
||||
prefix + text.mb_chars[start_pos..end_pos].strip + postfix
|
||||
else
|
||||
nil
|
||||
end
|
||||
end
|
||||
|
||||
|
|
Loading…
Reference in a new issue