Class: LLM::Object

Inherits:
BasicObject
Includes:
Enumerable
Defined in:
lib/llm/object.rb,
lib/llm/object/kernel.rb,
lib/llm/object/builder.rb

Overview

The LLM::Object class encapsulates a Hash object, and it allows a consumer to get and set Hash keys via regular methods. It is similar in spirit to OpenStruct, and it was introduced after OpenStruct became a bundled gem (and not a default gem) in Ruby 3.5.

Direct Known Subclasses

Model

Instance Method Summary collapse

Constructor Details

#initialize(h = {}) ⇒ LLM::Object

Parameters:

  • h (Hash) (defaults to: {})


20
21
22
# File 'lib/llm/object.rb', line 20

def initialize(h = {})
  @h = h.transform_keys(&:to_sym) || h
end

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

#method_missing(m, *args, &b) ⇒ Object (private)



68
69
70
71
72
73
74
75
76
# File 'lib/llm/object.rb', line 68

def method_missing(m, *args, &b)
  if m.to_s.end_with?("=")
    @h[m[0..-2].to_sym] = args.first
  elsif @h.key?(m)
    @h[m]
  else
    nil
  end
end

Instance Method Details

#[]=(k, v) ⇒ void

This method returns an undefined value.

Parameters:

  • k (Symbol, #to_sym)
  • v (Object)


44
45
46
# File 'lib/llm/object.rb', line 44

def []=(k, v)
  @h[k.to_sym] = v
end

#each {|k, v| ... } ⇒ void

This method returns an undefined value.

Yields a key value pair to a block.

Yield Parameters:



29
30
31
# File 'lib/llm/object.rb', line 29

def each(&)
  @h.each(&)
end

#[](k) ⇒ Object

Parameters:

  • k (Symbol, #to_sym)

Returns:



36
37
38
# File 'lib/llm/object.rb', line 36

def [](k)
  @h[k.to_sym]
end

#to_jsonString

Returns:

  • (String)


50
51
52
# File 'lib/llm/object.rb', line 50

def to_json(...)
  to_h.to_json(...)
end

#empty?Boolean

Returns:

  • (Boolean)


56
57
58
# File 'lib/llm/object.rb', line 56

def empty?
  @h.empty?
end

#to_hHash

Returns:

  • (Hash)


62
63
64
# File 'lib/llm/object.rb', line 62

def to_h
  @h
end