Module: LlmCostTracker::Parsers::UrlMatchers

Included in:
Base, Base
Defined in:
lib/llm_cost_tracker/parsers/base.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)


10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
# File 'lib/llm_cost_tracker/parsers/base.rb', line 10

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

    next false unless host_match && path_match
    next false unless extra_match

    true
  end
end

#parsed_uri(url) ⇒ Object



34
35
36
37
38
# File 'lib/llm_cost_tracker/parsers/base.rb', line 34

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)


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

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)


29
30
31
32
# File 'lib/llm_cost_tracker/parsers/base.rb', line 29

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