Merge pull request #1026 from chrishunt/link-twitter-handles

Link Twitter handles and hashtags in Twitter onebox
This commit is contained in:
Sam 2013-06-16 16:50:57 -07:00
commit 4650ce3556
2 changed files with 94 additions and 3 deletions

View File

@ -24,15 +24,50 @@ module Oneboxer
result['created_at'] = result['created_at'] =
Time.parse(result['created_at']).strftime("%I:%M%p - %d %b %y") Time.parse(result['created_at']).strftime("%I:%M%p - %d %b %y")
URI.extract(result['text'], %w(http https)).each do |url| result['text'] = link_all_the_things_in result['text']
result['text'].gsub!(url, "<a href='#{url}' target='_blank'>#{url}</a>")
end
result result
end end
private private
def link_all_the_things_in(text)
link_hashtags_in link_handles_in link_urls_in(text)
end
def link_urls_in(text)
URI.extract(text, %w(http https)).each do |url|
text.gsub!(url, "<a href='#{url}' target='_blank'>#{url}</a>")
end
text
end
def link_handles_in(text)
text.scan(/\s@(\w+)/).flatten.uniq.each do |handle|
text.gsub!("@#{handle}", [
"<a href='https://twitter.com/#{handle}' target='_blank'>",
"@#{handle}",
"</a>"
].join)
end
text
end
def link_hashtags_in(text)
text.scan(/\s#(\w+)/).flatten.uniq.each do |hashtag|
text.gsub!("##{hashtag}", [
"<a href='https://twitter.com/search?q=%23#{hashtag}' ",
"target='_blank'>",
"##{hashtag}",
"</a>"
].join)
end
text
end
def tweet_for(id) def tweet_for(id)
request = Net::HTTP::Get.new(tweet_uri_for id) request = Net::HTTP::Get.new(tweet_uri_for id)

View File

@ -0,0 +1,56 @@
require 'spec_helper'
describe Oneboxer::TwitterOnebox do
subject { described_class.new(nil, nil) }
let(:data) { %({ "text":"#{text}", "created_at":"#{created_at}" }) }
let(:text) { '' }
let(:created_at) { '2013-06-13T22:37:05Z' }
describe '#parse' do
it 'formats the timestamp' do
expect(subject.parse(data)['created_at']).to eq '10:37PM - 13 Jun 13'
end
context 'when text contains a url' do
let(:text) { 'Twitter http://twitter.com' }
it 'wraps eack url in a link' do
expect(subject.parse(data)['text']).to eq([
"Twitter ",
"<a href='http://twitter.com' target='_blank'>",
"http://twitter.com",
"</a>"
].join)
end
end
context 'when the text contains a twitter handle' do
let(:text) { 'I like @chrishunt' }
it 'wraps each handle in a link' do
expect(subject.parse(data)['text']).to eq([
"I like ",
"<a href='https://twitter.com/chrishunt' target='_blank'>",
"@chrishunt",
"</a>"
].join)
end
end
context 'when the text contains a hashtag' do
let(:text) { 'No secrets. #NSA' }
it 'wraps each hashtag in a link' do
expect(subject.parse(data)['text']).to eq([
"No secrets. ",
"<a href='https://twitter.com/search?q=%23NSA' target='_blank'>",
"#NSA",
"</a>"
].join)
end
end
end
end