Class: LlmGateway::FluentMapper::MapperInstance

Inherits:
Object
  • Object
show all
Defined in:
lib/llm_gateway/fluent_mapper.rb

Instance Method Summary collapse

Constructor Details

#initialize(data, mappers, mappings) ⇒ MapperInstance

Returns a new instance of MapperInstance.



36
37
38
39
40
41
42
43
44
45
46
47
# File 'lib/llm_gateway/fluent_mapper.rb', line 36

def initialize(data, mappers, mappings)
  @data = data.respond_to?(:with_indifferent_access) ? data.with_indifferent_access : data
  @mappers = mappers
  @mappings = mappings
  @mapper_definitions = {}

  # Execute mapper definitions
  mappers.each do |name, block|
    @mapper_definitions[name] = MapperDefinition.new
    @mapper_definitions[name].instance_eval(&block)
  end
end

Instance Method Details

#callObject



49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
# File 'lib/llm_gateway/fluent_mapper.rb', line 49

def call
  result = {}

  @mappings.each do |mapping|
    field = mapping[:field]
    options = mapping[:options]
    block = mapping[:block]

    from_path = options[:from] || field.to_s
    default_value = options[:default]

    value = get_nested_value(@data, from_path)
    value = default_value if value.nil? && !default_value.nil?

    value = instance_exec(field, value, &block) if block

    result[field] = value
  end

  LlmGateway::Utils.deep_symbolize_keys(result)
end

#map_collection(collection, options = {}) ⇒ Object



102
103
104
105
106
107
108
# File 'lib/llm_gateway/fluent_mapper.rb', line 102

def map_collection(collection, options = {})
  default_value = options[:default]
  return default_value if collection.nil? && !default_value.nil?
  return [] if collection.nil?

  collection.map { |item| map_single(item, options) }
end

#map_single(data, options = {}) ⇒ Object



71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
# File 'lib/llm_gateway/fluent_mapper.rb', line 71

def map_single(data, options = {})
  mapper_name = options[:with]
  default_value = options[:default]
  return default_value if data.nil? && !default_value.nil?
  return data unless mapper_name && @mapper_definitions[mapper_name]

  # Apply with_indifferent_access to data
  data = data.respond_to?(:with_indifferent_access) ? data.with_indifferent_access : data

  mapper_def = @mapper_definitions[mapper_name]
  result = {}

  mapper_def.mappings.each do |mapping|
    field = mapping[:field]
    map_options = mapping[:options]
    block = mapping[:block]

    from_path = map_options[:from] || field.to_s
    field_default_value = map_options[:default]

    value = get_nested_value(data, from_path)
    value = field_default_value if value.nil? && !field_default_value.nil?

    value = instance_exec(field, value, &block) if block

    result[field.to_s] = value
  end

  result
end