# frozen_string_literal: true require "yaml" # 🐵 patches eager-loading and cacheing of the default user_agent patterns # PR to add the functionality for reals: https://github.com/ua-parser/uap-ruby/pull/56 module UserAgentParser class Parser class Patterns def initialize @cache = {} get # warm the cache for the default patterns end def get(path = nil) path = UserAgentParser::DefaultPatternsPath if path.nil? @cache[path] ||= load_and_parse(path) end private def load_and_parse(path) yml = YAML.load_file(path) # Parse all the regexs yml.each_pair do |_type, patterns| patterns.each do |pattern| pattern[:regex] = Regexp.new(pattern["regex"], pattern["regex_flag"] == "i") end end [yml["user_agent_parsers"], yml["os_parsers"], yml["device_parsers"]] end end # rubocop:disable Style/ClassVars @@patterns = Patterns.new def self.load_patterns(path) @@patterns.get(path) end def initialize(options = {}) @patterns_path = options[:patterns_path] @ua_patterns, @os_patterns, @device_patterns = Parser.load_patterns(@patterns_path) end end end