# HG changeset patch # User nanaya # Date 1533231085 -32400 # Node ID 5af9b537db86a976b127fb43dc20a3ef86137829 # Parent 59a4645fd24cc8a7bc8bbcc98812ee4c694054f4 Unbreak \everything/ - simplify routing, no more split hackery - fix user lookup and differentiate between id and name lookup diff -r 59a4645fd24c -r 5af9b537db86 app/controllers/tweets_controller.rb --- a/app/controllers/tweets_controller.rb Fri Aug 03 02:12:54 2018 +0900 +++ b/app/controllers/tweets_controller.rb Fri Aug 03 02:31:25 2018 +0900 @@ -1,34 +1,26 @@ class TweetsController < ApplicationController - before_action :validate_id, :only => :show - def index - return try_redirect if params[:id] + return redirect if params[:id] || params[:name] end def show - client = Tweet.new(params[:id]) + return redirect if params[:id][/D/].present? + + client = Tweet.new(params[:id].to_i) + @user = client.user + + return redirect if @user.screen_name != params[:name] + @tweets = client.timeline - @user = client.user rescue Twitter::Error::NotFound head :not_found rescue Twitter::Error::Unauthorized head :forbidden end - private - - def validate_id - id = params[:id].split("/")[0] - if id[/\D/].nil? - params[:id] = id - else - try_redirect - end - end - - def try_redirect - user = Tweet.new(params[:id]).user - redirect_to tweet_path("#{user.id}/#{user.screen_name}") + def redirect + @user ||= Tweet.new(params[:id] || params[:name]).user + redirect_to tweet_path(@user.id, @user.screen_name) rescue Twitter::Error::NotFound head :not_found rescue Twitter::Error::Unauthorized diff -r 59a4645fd24c -r 5af9b537db86 app/models/tweet.rb --- a/app/models/tweet.rb Fri Aug 03 02:12:54 2018 +0900 +++ b/app/models/tweet.rb Fri Aug 03 02:31:25 2018 +0900 @@ -12,7 +12,7 @@ def initialize(twitter_id) @clients = {} - @twitter_id = twitter_id.to_s + @twitter_id = twitter_id end def id @@ -47,12 +47,13 @@ def user if @user.nil? - raw = Rails.cache.fetch("user:v1:#{@twitter_id}", :expires_in => self.class.cache_expires_time) do + cache_key = "user:v1:#{@twitter_id.is_a?(Integer) ? 'id' : 'lookup'}:#{@twitter_id}" + raw = Rails.cache.fetch(cache_key, :expires_in => self.class.cache_expires_time) do client_try(:user, @twitter_id).tap do |data| if data[:result] == :ok user = data[:data] - if user.id.to_s != @twitter_id && user.screen_name != @twitter_id + if user.id != @twitter_id && user.screen_name.downcase != @twitter_id throw "Wrong user data. Requested: #{@twitter_id}, got: #{user.id} (#{user.screen_name.printable})" end end diff -r 59a4645fd24c -r 5af9b537db86 config/routes.rb --- a/config/routes.rb Fri Aug 03 02:12:54 2018 +0900 +++ b/config/routes.rb Fri Aug 03 02:31:25 2018 +0900 @@ -1,5 +1,6 @@ Rails.application.routes.draw do root "tweets#index" - get "*id" => "tweets#show", :defaults => { :format => :atom }, :as => "tweet" + get ":id/:name" => "tweets#show", :defaults => { :format => :atom }, :as => "tweet" + get ":name" => "tweets#redirect" end