Module: LlmCostTracker::Parsers::UrlMatchers

Included in:
Base, Base
Defined in:
lib/llm_cost_tracker/parsers.rb

Instance Method Summary collapse

Instance Method Details

#match_uri?(url, hosts: nil, exact_paths: nil, path_includes: nil, path_suffixes: nil, path_pattern: nil) ⇒ Boolean

Returns:

  • (Boolean)


39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
# File 'lib/llm_cost_tracker/parsers.rb', line 39

def match_uri?(url, hosts: nil, exact_paths: nil, path_includes: nil, path_suffixes: nil, path_pattern: nil)
  uri_matches?(url) do |uri|
    host_match = hosts.nil? || hosts.include?(uri.host.to_s.downcase)
    path_match = path_matches?(
      uri,
      exact_paths: exact_paths,
      path_includes: path_includes,
      path_suffixes: path_suffixes,
      path_pattern: path_pattern
    )
    extra_match = block_given? ? yield(uri) : true

    !!(host_match && path_match && extra_match)
  end
end

#parsed_uri(url) ⇒ Object



60
61
62
63
64
# File 'lib/llm_cost_tracker/parsers.rb', line 60

def parsed_uri(url)
  URI.parse(url.to_s)
rescue URI::InvalidURIError
  nil
end

#path_matches?(uri, exact_paths: nil, path_includes: nil, path_suffixes: nil, path_pattern: nil) ⇒ Boolean

Returns:

  • (Boolean)


66
67
68
69
70
71
72
73
74
# File 'lib/llm_cost_tracker/parsers.rb', line 66

def path_matches?(uri, exact_paths: nil, path_includes: nil, path_suffixes: nil, path_pattern: nil)
  path = uri.path.to_s
  matches = true
  matches &&= exact_paths.include?(path) if exact_paths
  matches &&= Array(path_includes).all? { |fragment| path.include?(fragment) } if path_includes
  matches &&= path.match?(path_pattern) if path_pattern
  matches &&= path_suffixes.any? { |suffix| path == suffix || path.end_with?(suffix) } if path_suffixes
  matches
end

#uri_matches?(url) ⇒ Boolean

Returns:

  • (Boolean)


55
56
57
58
# File 'lib/llm_cost_tracker/parsers.rb', line 55

def uri_matches?(url)
  uri = parsed_uri(url)
  uri ? yield(uri) : false
end