From 8771afc5f53ac5b1da5b167c0605aed5397b4c4c Mon Sep 17 00:00:00 2001 From: joshua stein Date: Tue, 3 Feb 2015 11:20:07 -0600 Subject: [PATCH] try a bit harder at finding a submitted story's real title Ignore the title presented by the user unless we couldn't find anything, but start out by fetching the URL and trying some tags first, then , then use the title the user brought. --- app/controllers/stories_controller.rb | 4 +++- app/models/story.rb | 32 ++++++++++++++++++++++----- 2 files changed, 30 insertions(+), 6 deletions(-) diff --git a/app/controllers/stories_controller.rb b/app/controllers/stories_controller.rb index 4e9f002..ea55cc7 100644 --- a/app/controllers/stories_controller.rb +++ b/app/controllers/stories_controller.rb @@ -90,7 +90,9 @@ class StoriesController < ApplicationController end end - if params[:title].present? + # ignore what the user brought unless we need it as a fallback + @story.title = @story.fetched_title(request.remote_ip) + if !@story.title.present? && params[:title].present? @story.title = params[:title] end end diff --git a/app/models/story.rb b/app/models/story.rb index 60188e9..850a87d 100644 --- a/app/models/story.rb +++ b/app/models/story.rb @@ -253,12 +253,34 @@ class Story < ActiveRecord::Base end def fetched_title(for_remote_ip = nil) - doc = Nokogiri::HTML(fetched_content(for_remote_ip).to_s) - if doc - return doc.at_css("title").try(:text) - else - return "" + title = "" + + if !(doc = Nokogiri::HTML(fetched_content(for_remote_ip).to_s)) + return title end + + # try <meta property="og:title"> first, it probably won't have the site + # name + begin + title = doc.at_css("meta[property='og:title']"). + attributes["content"].text + rescue + end + + # then try <meta name="title"> + if title.to_s == "" + begin + title = doc.at_css("meta[name='title']").attributes["content"].text + rescue + end + end + + # then try plain old <title> + if title.to_s == "" + title = doc.at_css("title").try(:text).to_s + end + + return title end def generated_markeddown_description