Module: GroqRuby::Models::ModelFactory
- Included in:
- GroqRuby::MCP::Tool, Batch, BatchList, BatchRequestCounts, ChatCompletion, ChatCompletionChoice, ChatCompletionChunk, ChatCompletionChunkChoice, ChatCompletionDelta, ChatCompletionMessage, CreateEmbeddingResponse, Embedding, EmbeddingUsage, FileDeleted, FileList, FileObject, Model, ModelDeleted, ModelList, Transcription, Translation, Usage
- Defined in:
- lib/groq_ruby/models/model_factory.rb
Overview
Tiny mixin that gives a Data subclass a ‘from_hash` constructor. Walks the Data class’s ‘members` and pulls each key out of the incoming Hash (string-keyed). Unknown keys are ignored; missing keys default to `nil`. Per-attribute coercions are declared on the class:
class MyModel < Data.define(:choices)
extend ModelFactory
coerce :choices, with: ->(arr) { arr.map { |h| Choice.from_hash(h) } }
end
Instance Method Summary collapse
Instance Method Details
#coerce(attr, with:) ⇒ Object
13 14 15 |
# File 'lib/groq_ruby/models/model_factory.rb', line 13 def coerce(attr, with:) coercions[attr] = with end |
#coercions ⇒ Object
17 18 19 |
# File 'lib/groq_ruby/models/model_factory.rb', line 17 def coercions @coercions ||= {} end |
#from_hash(hash) ⇒ Object
21 22 23 24 25 26 27 28 |
# File 'lib/groq_ruby/models/model_factory.rb', line 21 def from_hash(hash) return nil if hash.nil? attrs = members.each_with_object({}) do |name, acc| raw = hash[name.to_s] || hash[name] acc[name] = coercions.key?(name) ? coercions[name].call(raw) : raw end new(**attrs) end |