mirror of
https://github.com/discourse/discourse.git
synced 2025-05-22 07:48:17 +08:00
FIX: Replace Twitter handles one at a time (#15870)
Previously, all handles and hashtags were replaced in one go which could result in a wrong result if a handle was a substring of another one.
This commit is contained in:
@ -95,28 +95,17 @@ class TwitterApi
|
|||||||
protected
|
protected
|
||||||
|
|
||||||
def link_handles_in(text)
|
def link_handles_in(text)
|
||||||
text.scan(/(?:^|\s)@(\w+)/).flatten.uniq.each do |handle|
|
text.gsub(/(?:^|\s)@\w+/) do |match|
|
||||||
text.gsub!(/(?:^|\s)@#{handle}/, [
|
handle = match.strip[1..]
|
||||||
" <a href='https://twitter.com/#{handle}' target='_blank'>",
|
"<a href='https://twitter.com/#{handle}' target='_blank'>@#{handle}</a>"
|
||||||
"@#{handle}",
|
end.strip
|
||||||
"</a>"
|
|
||||||
].join)
|
|
||||||
end
|
|
||||||
|
|
||||||
text.strip
|
|
||||||
end
|
end
|
||||||
|
|
||||||
def link_hashtags_in(text)
|
def link_hashtags_in(text)
|
||||||
text.scan(/(?:^|\s)#(\w+)/).flatten.uniq.each do |hashtag|
|
text.gsub(/(?:^|\s)#\w+/) do |match|
|
||||||
text.gsub!(/(?:^|\s)##{hashtag}/, [
|
hashtag = match.strip[1..]
|
||||||
" <a href='https://twitter.com/search?q=%23#{hashtag}' ",
|
"<a href='https://twitter.com/search?q=%23#{hashtag}' target='_blank'>##{hashtag}</a>"
|
||||||
"target='_blank'>",
|
end.strip
|
||||||
"##{hashtag}",
|
|
||||||
"</a>"
|
|
||||||
].join)
|
|
||||||
end
|
|
||||||
|
|
||||||
text.strip
|
|
||||||
end
|
end
|
||||||
|
|
||||||
def user_timeline_uri_for(screen_name)
|
def user_timeline_uri_for(screen_name)
|
||||||
|
21
spec/lib/twitter_api_spec.rb
Normal file
21
spec/lib/twitter_api_spec.rb
Normal file
@ -0,0 +1,21 @@
|
|||||||
|
# frozen_string_literal: true
|
||||||
|
|
||||||
|
require 'rails_helper'
|
||||||
|
|
||||||
|
describe TwitterApi do
|
||||||
|
context '.link_handles_in' do
|
||||||
|
it 'correctly replaces handles' do
|
||||||
|
expect(TwitterApi.send(:link_handles_in, "@foo @foobar")).to match_html <<~HTML
|
||||||
|
<a href='https://twitter.com/foo' target='_blank'>@foo</a> <a href='https://twitter.com/foobar' target='_blank'>@foobar</a>
|
||||||
|
HTML
|
||||||
|
end
|
||||||
|
end
|
||||||
|
|
||||||
|
context '.link_hashtags_in' do
|
||||||
|
it 'correctly replaces hashtags' do
|
||||||
|
expect(TwitterApi.send(:link_hashtags_in, "#foo #foobar")).to match_html <<~HTML
|
||||||
|
<a href='https://twitter.com/search?q=%23foo' target='_blank'>#foo</a> <a href='https://twitter.com/search?q=%23foobar' target='_blank'>#foobar</a>
|
||||||
|
HTML
|
||||||
|
end
|
||||||
|
end
|
||||||
|
end
|
Reference in New Issue
Block a user