From 1fb97f8bbae0468ae6366e5ce6a98ae030fe9a13 Mon Sep 17 00:00:00 2001 From: Dan Ungureanu Date: Wed, 9 Feb 2022 13:54:02 +0200 Subject: [PATCH] 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. --- lib/twitter_api.rb | 27 ++++++++------------------- spec/lib/twitter_api_spec.rb | 21 +++++++++++++++++++++ 2 files changed, 29 insertions(+), 19 deletions(-) create mode 100644 spec/lib/twitter_api_spec.rb diff --git a/lib/twitter_api.rb b/lib/twitter_api.rb index 5664bb2a263..85155dd2e3a 100644 --- a/lib/twitter_api.rb +++ b/lib/twitter_api.rb @@ -95,28 +95,17 @@ class TwitterApi protected def link_handles_in(text) - text.scan(/(?:^|\s)@(\w+)/).flatten.uniq.each do |handle| - text.gsub!(/(?:^|\s)@#{handle}/, [ - " ", - "@#{handle}", - "" - ].join) - end - - text.strip + text.gsub(/(?:^|\s)@\w+/) do |match| + handle = match.strip[1..] + "@#{handle}" + end.strip end def link_hashtags_in(text) - text.scan(/(?:^|\s)#(\w+)/).flatten.uniq.each do |hashtag| - text.gsub!(/(?:^|\s)##{hashtag}/, [ - " ", - "##{hashtag}", - "" - ].join) - end - - text.strip + text.gsub(/(?:^|\s)#\w+/) do |match| + hashtag = match.strip[1..] + "##{hashtag}" + end.strip end def user_timeline_uri_for(screen_name) diff --git a/spec/lib/twitter_api_spec.rb b/spec/lib/twitter_api_spec.rb new file mode 100644 index 00000000000..7af55b842db --- /dev/null +++ b/spec/lib/twitter_api_spec.rb @@ -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 + @foo @foobar + 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 + #foo #foobar + HTML + end + end +end