From 98ea6d94abde5795e3b321b9b39b39843cab3ba0 Mon Sep 17 00:00:00 2001 From: Nando Vieira Date: Fri, 2 Oct 2020 10:58:29 -0700 Subject: [PATCH] Delay parsing AcceptLanguage until `Browser::Base#accept_language` is first called (#499) Co-authored-by: Keiji Yoshimi --- CHANGELOG.md | 7 ++++++- lib/browser/base.rb | 14 +++++++++----- test/browser_test.rb | 2 +- 3 files changed, 16 insertions(+), 7 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index b6c09269..00c03859 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,10 @@ # Changelog +## Unreleased + +- Delay parsing `Accept-Language` until `Browser::Base#accept_language` is + called for the first time. + ## 5.0.0 - Rename `Browser::Platform#other?` to `Browser::Platform#unknown?`. @@ -18,7 +23,7 @@ - Fix QQ detection. - Fix Alipay detection. - Add Sougou Browser detection. -- User agent has a size limit of 512 bytes. This can be customized through +- User agent has a size limit of 512 bytes. This can be customized through `Browser.user_agent_size_limit`. - Accept-Language has a size limit of 256 bytes. This can be customized through `Browser.accept_language_size_limit`. diff --git a/lib/browser/base.rb b/lib/browser/base.rb index 4ddd07f4..11aba7e6 100644 --- a/lib/browser/base.rb +++ b/lib/browser/base.rb @@ -6,15 +6,11 @@ class Base attr_reader :ua - # Return an array with all preferred languages that this browser accepts. - attr_reader :accept_language - def initialize(ua, accept_language: nil) validate_size(:user_agent, ua.to_s) - validate_size(:accept_language, accept_language.to_s) @ua = ua - @accept_language = AcceptLanguage.parse(accept_language) + @accept_language_raw = accept_language.to_s end # Return a meta info about this browser. @@ -22,6 +18,14 @@ def meta Meta.get(self) end + # Return an array with all preferred languages that this browser accepts. + def accept_language + @accept_language ||= begin + validate_size(:accept_language, @accept_language_raw) + AcceptLanguage.parse(@accept_language_raw) + end + end + alias_method :to_a, :meta # Return meta representation as string. diff --git a/test/browser_test.rb b/test/browser_test.rb index 8795e96c..25726c5b 100644 --- a/test/browser_test.rb +++ b/test/browser_test.rb @@ -169,7 +169,7 @@ class BrowserTest < Minitest::Test "is 257 bytes" assert_raises(Browser::Error, message) do - Browser.new("Chrome", accept_language: "a" * 257) + Browser.new("Chrome", accept_language: "a" * 257).accept_language end end end