Module: LlmCostTracker::Integrations::ObjectReader

Defined in:
lib/llm_cost_tracker/integrations/object_reader.rb

Class Method Summary collapse

Class Method Details

.first(object, *keys) ⇒ Object



8
9
10
11
12
13
14
# File 'lib/llm_cost_tracker/integrations/object_reader.rb', line 8

def first(object, *keys)
  keys.each do |key|
    value = read(object, key)
    return value unless value.nil?
  end
  nil
end

.integer(value) ⇒ Object



30
31
32
# File 'lib/llm_cost_tracker/integrations/object_reader.rb', line 30

def integer(value)
  value.nil? ? 0 : value.to_i
end

.nested(object, *path) ⇒ Object



16
17
18
19
20
21
22
# File 'lib/llm_cost_tracker/integrations/object_reader.rb', line 16

def nested(object, *path)
  path.reduce(object) do |current, key|
    return nil if current.nil?

    read(current, key)
  end
end

.read(object, key) ⇒ Object



24
25
26
27
28
# File 'lib/llm_cost_tracker/integrations/object_reader.rb', line 24

def read(object, key)
  return nil if object.nil?

  read_hash(object, key) || read_method(object, key) || read_index(object, key)
end

.read_hash(object, key) ⇒ Object



34
35
36
37
38
39
40
41
# File 'lib/llm_cost_tracker/integrations/object_reader.rb', line 34

def read_hash(object, key)
  return unless object.respond_to?(:key?)

  return object[key] if object.key?(key)

  string_key = key.to_s
  object[string_key] if object.key?(string_key)
end

.read_index(object, key) ⇒ Object



47
48
49
50
51
52
53
# File 'lib/llm_cost_tracker/integrations/object_reader.rb', line 47

def read_index(object, key)
  return unless object.respond_to?(:[])

  object[key]
rescue IndexError, TypeError, NoMethodError
  nil
end

.read_method(object, key) ⇒ Object



43
44
45
# File 'lib/llm_cost_tracker/integrations/object_reader.rb', line 43

def read_method(object, key)
  object.public_send(key) if object.respond_to?(key)
end