From 78cba885d92cd9f52a5e81ec15c9ec89e80115b8 Mon Sep 17 00:00:00 2001 From: Philipp Fehre Date: Mon, 15 May 2017 15:55:28 +0100 Subject: [PATCH] Testing header presensce Allowing to easily determine if a header is actually present in the HTTP connection. This is useful to determine if when using `best_of` the fallback should be a global fallback for the header or whatever is returned by `best_of`. This avoids relying on the ordering of options passed to `best_of`, as without a presence check the selected option would be the first option passed. --- lib/rack/accept/header.rb | 6 ++++++ test/language_test.rb | 7 +++++++ 2 files changed, 13 insertions(+) diff --git a/lib/rack/accept/header.rb b/lib/rack/accept/header.rb index 98c24d3..aa157ab 100644 --- a/lib/rack/accept/header.rb +++ b/lib/rack/accept/header.rb @@ -98,6 +98,12 @@ def accept?(value) qvalue(value) != 0 end + # Determines if the given header had a +value+ set, if not the header can + # be regarded as not having been present in the HTTP connection. + def present? + !values.empty? + end + # Returns a copy of the given +values+ array, sorted by quality factor # (qvalue). Each element of the returned array is itself an array # containing two objects: 1) the value's qvalue and 2) the original diff --git a/test/language_test.rb b/test/language_test.rb index 54cade1..0354092 100644 --- a/test/language_test.rb +++ b/test/language_test.rb @@ -13,6 +13,13 @@ def test_qvalue assert_equal(0, l.qvalue('da')) end + def test_present? + header = 'da, en-gb;q=0.8, en;q=0.7' + assert_true(L.new(header).present?) + header = '' + assert_false(L.new(header).present?) + end + def test_matches l = L.new('da, *, en') assert_equal(%w{*}, l.matches(''))