From 025558f6ad98930aa7186ebfed764d9c8f6b762d Mon Sep 17 00:00:00 2001 From: joshua stein Date: Thu, 3 Apr 2014 13:20:24 -0500 Subject: [PATCH] add support for /top and things like /top/3m and /top/2w not linked to from anywhere yet closes #95 --- app/controllers/home_controller.rb | 36 +++++++++++++++++++++++++++++- config/routes.rb | 5 +++++ 2 files changed, 40 insertions(+), 1 deletion(-) diff --git a/app/controllers/home_controller.rb b/app/controllers/home_controller.rb index 03a148b..932c53c 100644 --- a/app/controllers/home_controller.rb +++ b/app/controllers/home_controller.rb @@ -127,6 +127,30 @@ class HomeController < ApplicationController end end + TOP_INTVS = { "d" => "Day", "w" => "Week", "m" => "Month", "y" => "Year" } + def top + @cur_url = "/top" + length = { :dur => 1, :intv => "Week" } + + if m = params[:length].to_s.match(/\A(\d+)([#{TOP_INTVS.keys.join}])\z/) + length[:dur] = m[1].to_i + length[:intv] = TOP_INTVS[m[2]] + + @cur_url << "/#{params[:length]}" + end + + @stories = find_stories({ :top => true, :length => length }) + + if length[:dur] > 1 + @heading = @title = "Top Stories of the Past #{length[:dur]} " << + length[:intv] << "s" + else + @heading = @title = "Top Stories of the Past " << length[:intv] + end + + render :action => "index" + end + private def find_stories(how = {}) @page = how[:page] = 1 @@ -242,6 +266,16 @@ private break end end + elsif how[:top] && how[:length] + stories = stories.where("created_at >= (NOW() - INTERVAL " << + "#{how[:length][:dur]} #{how[:length][:intv].upcase})") + end + + order = "hotness" + if how[:newest] || how[:recent] + order = "stories.created_at DESC" + elsif how[:top] + order = "(CAST(upvotes AS integer) - CAST(downvotes AS integer)) DESC" end stories = stories.includes( @@ -251,7 +285,7 @@ private ).offset( (how[:page] - 1) * STORIES_PER_PAGE ).order( - (how[:newest] || how[:recent]) ? "stories.created_at DESC" : "hotness" + order ).to_a show_more = false diff --git a/config/routes.rb b/config/routes.rb index 5d93a03..d84d527 100644 --- a/config/routes.rb +++ b/config/routes.rb @@ -17,6 +17,11 @@ Lobsters::Application.routes.draw do get "/hidden" => "home#hidden" get "/hidden/page/:page" => "home#hidden" + get "/top" => "home#top" + get "/top/page/:page" => "home#top" + get "/top/:length" => "home#top" + get "/top/:length/page/:page" => "home#top" + get "/threads" => "comments#threads" get "/threads/:user" => "comments#threads"