Limit results by quantity

Stephen Paul Weber created

Don't just include it in the queries

Change summary

lib/tel_selections.rb | 37 ++++++++++++++++---------------------
1 file changed, 16 insertions(+), 21 deletions(-)

Detailed changes

lib/tel_selections.rb 🔗

@@ -94,13 +94,13 @@ class TelSelections
 				qs = form.field("q")&.value.to_s.strip
 				return Tn.for_pending_value(qs) if qs =~ /\A\+1\d{10}\Z/
 
+				quantity = Quantity.for(form)
 				q = Q.for(feelinglucky(qs, form), db: db, memcache: memcache)
 
 				new(
 					q.iris_query
-					.merge(enableTNDetail: true, LCA: false)
-					.merge(Quantity.for(form).iris_query),
-					q.sql_query,
+					.merge(enableTNDetail: true, LCA: false),
+					q.sql_query, quantity,
 					fallback: q.fallback, memcache: memcache, db: db
 				)
 			end
@@ -115,10 +115,12 @@ class TelSelections
 			end
 
 			def initialize(
-				iris_query, sql_query, fallback: [], memcache: MEMCACHE, db: DB
+				iris_query, sql_query, quantity,
+				fallback: [], memcache: MEMCACHE, db: DB
 			)
-				@iris_query = iris_query
+				@iris_query = iris_query.merge(quantity.iris_query)
 				@sql_query = sql_query
+				@quantity = quantity
 				@fallback = fallback
 				@memcache = memcache
 				@db = db
@@ -131,7 +133,7 @@ class TelSelections
 				end
 				return next_fallback if result.empty? && !@fallback.empty?
 
-				result
+				@quantity.limit(result)
 			end
 
 			def fetch_bandwidth_inventory
@@ -156,10 +158,9 @@ class TelSelections
 				@memcache.set(cache_key, CBOR.encode([]), 43200)
 				fallback = @fallback.shift
 				self.class.new(
-					fallback.iris_query.merge(
-						enableTNDetail: true, quantity: @iris_query[:quantity]
-					),
+					fallback.iris_query.merge(enableTNDetail: true),
 					fallback.sql_query,
+					@quantity,
 					fallback: @fallback,
 					memcache: @memcache, db: @db
 				).tns
@@ -178,9 +179,7 @@ class TelSelections
 
 			class Quantity
 				def self.for(form)
-					if form.field(ACTION_FIELD)&.value == "feelinglucky"
-						return Default.new
-					end
+					return new(10) if form.field(ACTION_FIELD)&.value == "feelinglucky"
 
 					rsm_max = form.find(
 						"ns:set/ns:max",
@@ -188,23 +187,19 @@ class TelSelections
 					).first
 					return new(rsm_max.content.to_i) if rsm_max
 
-					Default.new
+					new(10)
 				end
 
 				def initialize(quantity)
 					@quantity = quantity
 				end
 
-				def iris_query
-					{ quantity: [@quantity, 100].min }
+				def limit(result)
+					(result || [])[0..@quantity - 1]
 				end
 
-				# NOTE: Gajim sends back the whole list on submit, so big
-				# lists can cause issues
-				class Default
-					def iris_query
-						{ quantity: 10 }
-					end
+				def iris_query
+					{ quantity: [@quantity, 100].min }
 				end
 			end
 		end