Class: Text::Gen::Runner

Inherits:
Object
  • Object
show all
Defined in:
lib/text/gen/runner.rb

Overview

Runner generates results from the builder that is found with the given key.

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(key:, lookup:, max_recursion: 10, max_attempts: 10, filters: [], meta: {}) ⇒ Runner

Returns a new instance of Runner.



12
13
14
15
16
17
18
19
# File 'lib/text/gen/runner.rb', line 12

def initialize(key:, lookup:, max_recursion: 10, max_attempts: 10, filters: [], meta: {})
  @key = key.to_s.downcase
  @lookup = lookup
  @filters = filters
  @meta = meta
  @max_attempts = max_attempts
  @max_recursion = max_recursion
end

Instance Attribute Details

#filtersObject (readonly)

Returns the value of attribute filters.



10
11
12
# File 'lib/text/gen/runner.rb', line 10

def filters
  @filters
end

#keyObject (readonly)

Returns the value of attribute key.



10
11
12
# File 'lib/text/gen/runner.rb', line 10

def key
  @key
end

#lookupObject (readonly)

Returns the value of attribute lookup.



10
11
12
# File 'lib/text/gen/runner.rb', line 10

def lookup
  @lookup
end

#max_attemptsObject (readonly)

Returns the value of attribute max_attempts.



10
11
12
# File 'lib/text/gen/runner.rb', line 10

def max_attempts
  @max_attempts
end

#max_recursionObject (readonly)

Returns the value of attribute max_recursion.



10
11
12
# File 'lib/text/gen/runner.rb', line 10

def max_recursion
  @max_recursion
end

#metaObject (readonly)

Returns the value of attribute meta.



10
11
12
# File 'lib/text/gen/runner.rb', line 10

def meta
  @meta
end

Instance Method Details

#calculate_total_weight(context, items) ⇒ Object



225
226
227
228
229
230
231
232
233
# File 'lib/text/gen/runner.rb', line 225

def calculate_total_weight(context, items)
  sum = 0
  items.each do |item|
    weight = calculate_weight(context, item)
    item["weight"] = weight
    sum += weight
  end
  sum
end

#calculate_weight(context, item) ⇒ Object



205
206
207
208
209
210
211
212
213
214
# File 'lib/text/gen/runner.rb', line 205

def calculate_weight(context, item)
  weight = item["weight"]
  if weight == "*"
    reference = item["segments"]&.find { |s| s["type"] == "reference" }
    key = reference&.fetch("text")
    weight = lookup_and_count_items(context, key)
  end

  weight.to_i < 1 ? 1 : weight.to_i
end

#lookup_and_count_items(context, key) ⇒ Object



216
217
218
219
220
221
222
223
# File 'lib/text/gen/runner.rb', line 216

def lookup_and_count_items(context, key)
  return 0 unless key

  builder = context.store.fetch(key)
  return 0 unless builder

  builder["items"]&.size || 1
end

#random_from_dice(text) ⇒ Object



235
236
237
238
239
240
241
242
243
# File 'lib/text/gen/runner.rb', line 235

def random_from_dice(text)
  rolled = DiceNomShim.roll(text)
  parsed = JSON.parse(rolled).first["lhs"]

  # Keep tracks the dice that weren't discarded
  count = parsed["values"].select { |v| v["keep"] }.count
  total = parsed["total"]
  [total, count]
end

#random_item(items, dice: nil) ⇒ Object



124
125
126
127
128
129
130
131
132
# File 'lib/text/gen/runner.rb', line 124

def random_item(items, dice: nil)
  return items.sample if dice.nil? || dice.empty? || dice == "*"

  total, count = random_from_dice(dice)
  index = total - count # convert to 0-indexed
  raise NoItemMatched("roll #{total} exceeds #{items.length}") if index >= items.length

  items[index]
end

#run(count: 1) ⇒ Object

Raises:



21
22
23
24
25
26
27
28
29
30
# File 'lib/text/gen/runner.rb', line 21

def run(count: 1)
  store = Store.new(lookup)
  builder = store.fetch(key)
  raise NoBuilderMatched, "{builder `#{key}` not found}" unless builder

  context = Context.new(store:, filters:, meta:, max_recursion:)
  ResultAccumulator.accumulate(count:, max_attempts:) do
    run_builder(context, builder)
  end
end

#run_builder(context, builder) ⇒ Object

A builder is hash with a key field, items, filters, and meta



33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
# File 'lib/text/gen/runner.rb', line 33

def run_builder(context, builder)
  context.descend!(builder)
  checkpoint = context.remember_checkpoint
  context.with_filters(builder["filters"]) do
    builder = context.apply_builder_filters(builder)
    unless builder
      context.restore_remember(checkpoint)
      return
    end

    # Filter mapping of builder to result is allowed
    return builder if builder.is_a?(Result)

    result = builder.is_a?(Result) ? builder : run_items(context, builder["items"])
    unless result
      context.restore_remember(checkpoint)
      return
    end

    result.merge_meta(builder["meta"])
    result = context.apply_result_filters(result)
    unless result
      context.restore_remember(checkpoint)
      return
    end

    context.restore_remember(checkpoint)
    context.remember(result)
  end
ensure
  context.ascend!
end

#run_dice_segment(seg) ⇒ Object



183
184
185
186
# File 'lib/text/gen/runner.rb', line 183

def run_dice_segment(seg)
  total, = random_from_dice(seg["text"])
  Result.new(text: total.to_s, multiplier: total, type: :dice)
end

#run_item(context, item) ⇒ Object



134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
# File 'lib/text/gen/runner.rb', line 134

def run_item(context, item)
  item = context.apply_item_filters(item)
  return unless item

  # Filter mapping of item to result is allowed
  return item if item.is_a?(Result)

  context.with_filters(item["filters"]) do
    results = item["segments"].map { |seg| run_segment(context, seg) }
    return if results.any?(&:nil?) || results.empty?

    result = Result.merge(results,
                 value: item["value"],
                 multiplier: item["multiplier"],
                 meta: item["meta"],
                 type: context.current_key)
    context.apply_result_filters(result)
  end
end

#run_item_sequence(context, items) ⇒ Object



80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
# File 'lib/text/gen/runner.rb', line 80

def run_item_sequence(context, items)
  results = items.map do |item|
    weight = item["weight"]&.to_i || 100
    next unless rand(100) < weight.clamp(1, 100)

    ResultAccumulator.accumulate(count: 1, max_attempts: @max_attempts) do
      run_item(context, item)
    end.first
  end

  results = results.compact
  return if results.empty?

  Result.merge(results, separator: context.current_modifier, type: :sequence)
end

#run_items(context, items) ⇒ Object



66
67
68
69
70
71
72
73
74
75
76
77
78
# File 'lib/text/gen/runner.rb', line 66

def run_items(context, items)
  items = context.apply_item_list_filters(items)
  return if items.empty?

  case context.current_strategy
  when "sample"
    run_random_item(context, items)
  when "sequence"
    run_item_sequence(context, items)
  else
    run_weighted_items(context, items)
  end
end

#run_number_segment(seg) ⇒ Object



188
189
190
191
# File 'lib/text/gen/runner.rb', line 188

def run_number_segment(seg)
  num = seg["text"].to_i
  Result.new(text: num.to_s, multiplier: num, type: :number)
end

#run_random_item(context, items) ⇒ Object



117
118
119
120
121
122
# File 'lib/text/gen/runner.rb', line 117

def run_random_item(context, items)
  item = random_item(items, dice: context.current_modifier)
  return unless item

  run_item(context, item)
end

#run_reference_segment(context, seg) ⇒ Object



193
194
195
196
197
198
199
200
201
202
203
# File 'lib/text/gen/runner.rb', line 193

def run_reference_segment(context, seg)
  key = seg["text"]

  builder = context.store.fetch(key)
  return unless builder

  # Offset by one to ensure the segment filters are applied to the builder
  context.with_filters(seg["filters"], offset: 1) do
    run_builder(context, builder)
  end
end

#run_segment(context, seg) ⇒ Object



154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
# File 'lib/text/gen/runner.rb', line 154

def run_segment(context, seg)
  # Note, a filter may expand a segment into multiple segments
  segments = context.apply_segment_filters(seg)
  return if segments.nil?

  # Filter mapping of segment to result is allowed
  return segments if segments.is_a?(Result)

  results = segments.map { |seg| run_simple_segment(context, seg) }.compact
  return if results.empty?

  return results[0] if results.length == 1

  Result.merge(results, type: "segment expansion")
end

#run_simple_segment(context, seg) ⇒ Object



170
171
172
173
174
175
176
177
178
179
180
181
# File 'lib/text/gen/runner.rb', line 170

def run_simple_segment(context, seg)
  case seg["type"]
  when "dice"
    run_dice_segment(seg)
  when "number"
    run_number_segment(seg)
  when "reference"
    run_reference_segment(context, seg)
  else
    Result.new(text: seg["text"], value: seg["value"], type: :constant)
  end
end

#run_weighted_items(context, items) ⇒ Object



96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
# File 'lib/text/gen/runner.rb', line 96

def run_weighted_items(context, items)
  total_weight = calculate_total_weight(context, items)
  dice = context.current_modifier
  rand_weight = if dice.nil? || dice.empty? || dice == "*"
                  rand(total_weight)
                else
                  total, count = random_from_dice(dice)
                  total - count # convert to 0-indexed
                end
  return if rand_weight > total_weight


  current_weight = 0
  item = items.find do |item|
    current_weight += [item.fetch("weight", 1).to_i, 1].max
    current_weight > rand_weight
  end

  run_item(context, item)
end