Ensure tweets fit twitter's length limit

This commit is contained in:
Karina Kwiatek 2021-12-25 13:39:35 +01:00
parent e5f0be70dc
commit 61c8208e26
1 changed files with 17 additions and 3 deletions

View File

@ -27,16 +27,30 @@ class Services::Twitter < Service
end
def prepare_tweet(answer)
# TODO: improve this.
question_content = twitter_markdown answer.question.content.gsub(/\@(\w+)/, '\1')
original_question_length = question_content.length
answer_content = twitter_markdown answer.content
original_answer_length = answer_content.length
answer_url = show_user_answer_url(
id: answer.id,
username: answer.user.screen_name,
host: APP_CONFIG['hostname'],
protocol: (APP_CONFIG['https'] ? :https : :http)
)
"#{question_content[0..122]}#{'…' if question_content.length > 123}" \
"#{answer_content[0..123]}#{'…' if answer_content.length > 124} #{answer_url}"
parsed_tweet = { :valid => false }
tweet_text = ""
until parsed_tweet[:valid]
tweet_text = "#{question_content[0..122]}#{'…' if original_question_length > question_content.length}" \
"#{answer_content[0..123]}#{'…' if original_answer_length > answer_content.length} #{answer_url}"
parsed_tweet = Twitter::TwitterText::Validation::parse_tweet(tweet_text)
question_content = question_content[0..-2]
answer_content = answer_content[0..-2]
end
tweet_text
end
end