text-gen 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
checksums.yaml ADDED
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA256:
3
+ metadata.gz: a797ffbcfad9d7ad94943ea650e8fa0fa92f88e305035b2085d9500849f3bd87
4
+ data.tar.gz: dbf62805408bd3258a0153d83a716e29d650d8f7c37cefaa2b9090a6518f3355
5
+ SHA512:
6
+ metadata.gz: 0a5df8167670c236ead54c4c9cb63abe9fd8340c46f0bda70eac50255189ca0aa21ac6cf6305ddd451f2d10ef3af0314262cd48955f801f4b8e1e7fa1cff0d7b
7
+ data.tar.gz: 7b1035f58a41888f6e48b3ae56cb948d49eed2b549128fb333d95f7df2686d5831156d4cfd3b271813cb44a387d406eadcfed6cf507e8236d98636b043ac752c
data/CHANGELOG.md ADDED
@@ -0,0 +1,5 @@
1
+ ## [Unreleased]
2
+
3
+ ## [0.1.0] - 2025-12-28
4
+
5
+ - Initial release
@@ -0,0 +1,132 @@
1
+ # Contributor Covenant Code of Conduct
2
+
3
+ ## Our Pledge
4
+
5
+ We as members, contributors, and leaders pledge to make participation in our
6
+ community a harassment-free experience for everyone, regardless of age, body
7
+ size, visible or invisible disability, ethnicity, sex characteristics, gender
8
+ identity and expression, level of experience, education, socio-economic status,
9
+ nationality, personal appearance, race, caste, color, religion, or sexual
10
+ identity and orientation.
11
+
12
+ We pledge to act and interact in ways that contribute to an open, welcoming,
13
+ diverse, inclusive, and healthy community.
14
+
15
+ ## Our Standards
16
+
17
+ Examples of behavior that contributes to a positive environment for our
18
+ community include:
19
+
20
+ * Demonstrating empathy and kindness toward other people
21
+ * Being respectful of differing opinions, viewpoints, and experiences
22
+ * Giving and gracefully accepting constructive feedback
23
+ * Accepting responsibility and apologizing to those affected by our mistakes,
24
+ and learning from the experience
25
+ * Focusing on what is best not just for us as individuals, but for the overall
26
+ community
27
+
28
+ Examples of unacceptable behavior include:
29
+
30
+ * The use of sexualized language or imagery, and sexual attention or advances of
31
+ any kind
32
+ * Trolling, insulting or derogatory comments, and personal or political attacks
33
+ * Public or private harassment
34
+ * Publishing others' private information, such as a physical or email address,
35
+ without their explicit permission
36
+ * Other conduct which could reasonably be considered inappropriate in a
37
+ professional setting
38
+
39
+ ## Enforcement Responsibilities
40
+
41
+ Community leaders are responsible for clarifying and enforcing our standards of
42
+ acceptable behavior and will take appropriate and fair corrective action in
43
+ response to any behavior that they deem inappropriate, threatening, offensive,
44
+ or harmful.
45
+
46
+ Community leaders have the right and responsibility to remove, edit, or reject
47
+ comments, commits, code, wiki edits, issues, and other contributions that are
48
+ not aligned to this Code of Conduct, and will communicate reasons for moderation
49
+ decisions when appropriate.
50
+
51
+ ## Scope
52
+
53
+ This Code of Conduct applies within all community spaces, and also applies when
54
+ an individual is officially representing the community in public spaces.
55
+ Examples of representing our community include using an official email address,
56
+ posting via an official social media account, or acting as an appointed
57
+ representative at an online or offline event.
58
+
59
+ ## Enforcement
60
+
61
+ Instances of abusive, harassing, or otherwise unacceptable behavior may be
62
+ reported to the community leaders responsible for enforcement at
63
+ [INSERT CONTACT METHOD].
64
+ All complaints will be reviewed and investigated promptly and fairly.
65
+
66
+ All community leaders are obligated to respect the privacy and security of the
67
+ reporter of any incident.
68
+
69
+ ## Enforcement Guidelines
70
+
71
+ Community leaders will follow these Community Impact Guidelines in determining
72
+ the consequences for any action they deem in violation of this Code of Conduct:
73
+
74
+ ### 1. Correction
75
+
76
+ **Community Impact**: Use of inappropriate language or other behavior deemed
77
+ unprofessional or unwelcome in the community.
78
+
79
+ **Consequence**: A private, written warning from community leaders, providing
80
+ clarity around the nature of the violation and an explanation of why the
81
+ behavior was inappropriate. A public apology may be requested.
82
+
83
+ ### 2. Warning
84
+
85
+ **Community Impact**: A violation through a single incident or series of
86
+ actions.
87
+
88
+ **Consequence**: A warning with consequences for continued behavior. No
89
+ interaction with the people involved, including unsolicited interaction with
90
+ those enforcing the Code of Conduct, for a specified period of time. This
91
+ includes avoiding interactions in community spaces as well as external channels
92
+ like social media. Violating these terms may lead to a temporary or permanent
93
+ ban.
94
+
95
+ ### 3. Temporary Ban
96
+
97
+ **Community Impact**: A serious violation of community standards, including
98
+ sustained inappropriate behavior.
99
+
100
+ **Consequence**: A temporary ban from any sort of interaction or public
101
+ communication with the community for a specified period of time. No public or
102
+ private interaction with the people involved, including unsolicited interaction
103
+ with those enforcing the Code of Conduct, is allowed during this period.
104
+ Violating these terms may lead to a permanent ban.
105
+
106
+ ### 4. Permanent Ban
107
+
108
+ **Community Impact**: Demonstrating a pattern of violation of community
109
+ standards, including sustained inappropriate behavior, harassment of an
110
+ individual, or aggression toward or disparagement of classes of individuals.
111
+
112
+ **Consequence**: A permanent ban from any sort of public interaction within the
113
+ community.
114
+
115
+ ## Attribution
116
+
117
+ This Code of Conduct is adapted from the [Contributor Covenant][homepage],
118
+ version 2.1, available at
119
+ [https://www.contributor-covenant.org/version/2/1/code_of_conduct.html][v2.1].
120
+
121
+ Community Impact Guidelines were inspired by
122
+ [Mozilla's code of conduct enforcement ladder][Mozilla CoC].
123
+
124
+ For answers to common questions about this code of conduct, see the FAQ at
125
+ [https://www.contributor-covenant.org/faq][FAQ]. Translations are available at
126
+ [https://www.contributor-covenant.org/translations][translations].
127
+
128
+ [homepage]: https://www.contributor-covenant.org
129
+ [v2.1]: https://www.contributor-covenant.org/version/2/1/code_of_conduct.html
130
+ [Mozilla CoC]: https://github.com/mozilla/diversity
131
+ [FAQ]: https://www.contributor-covenant.org/faq
132
+ [translations]: https://www.contributor-covenant.org/translations
data/LICENSE.txt ADDED
@@ -0,0 +1,21 @@
1
+ The MIT License (MIT)
2
+
3
+ Copyright (c) 2025 G Palmer
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in
13
+ all copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
21
+ THE SOFTWARE.
data/README.md ADDED
@@ -0,0 +1,43 @@
1
+ # Text::Gen
2
+
3
+ TODO: Delete this and the text below, and describe your gem
4
+
5
+ Welcome to your new gem! In this directory, you'll find the files you need to be able to package up your Ruby library into a gem. Put your Ruby code in the file `lib/text/gen`. To experiment with that code, run `bin/console` for an interactive prompt.
6
+
7
+ ## Installation
8
+
9
+ TODO: Replace `UPDATE_WITH_YOUR_GEM_NAME_IMMEDIATELY_AFTER_RELEASE_TO_RUBYGEMS_ORG` with your gem name right after releasing it to RubyGems.org. Please do not do it earlier due to security reasons. Alternatively, replace this section with instructions to install your gem from git if you don't plan to release to RubyGems.org.
10
+
11
+ Install the gem and add to the application's Gemfile by executing:
12
+
13
+ ```bash
14
+ bundle add UPDATE_WITH_YOUR_GEM_NAME_IMMEDIATELY_AFTER_RELEASE_TO_RUBYGEMS_ORG
15
+ ```
16
+
17
+ If bundler is not being used to manage dependencies, install the gem by executing:
18
+
19
+ ```bash
20
+ gem install UPDATE_WITH_YOUR_GEM_NAME_IMMEDIATELY_AFTER_RELEASE_TO_RUBYGEMS_ORG
21
+ ```
22
+
23
+ ## Usage
24
+
25
+ TODO: Write usage instructions here
26
+
27
+ ## Development
28
+
29
+ After checking out the repo, run `bin/setup` to install dependencies. Then, run `rake spec` to run the tests. You can also run `bin/console` for an interactive prompt that will allow you to experiment.
30
+
31
+ To install this gem onto your local machine, run `bundle exec rake install`. To release a new version, update the version number in `version.rb`, and then run `bundle exec rake release`, which will create a git tag for the version, push git commits and the created tag, and push the `.gem` file to [rubygems.org](https://rubygems.org).
32
+
33
+ ## Contributing
34
+
35
+ Bug reports and pull requests are welcome on GitHub at https://github.com/[USERNAME]/text-gen. This project is intended to be a safe, welcoming space for collaboration, and contributors are expected to adhere to the [code of conduct](https://github.com/[USERNAME]/text-gen/blob/master/CODE_OF_CONDUCT.md).
36
+
37
+ ## License
38
+
39
+ The gem is available as open source under the terms of the [MIT License](https://opensource.org/licenses/MIT).
40
+
41
+ ## Code of Conduct
42
+
43
+ Everyone interacting in the Text::Gen project's codebases, issue trackers, chat rooms and mailing lists is expected to follow the [code of conduct](https://github.com/[USERNAME]/text-gen/blob/master/CODE_OF_CONDUCT.md).
data/Rakefile ADDED
@@ -0,0 +1,12 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "bundler/gem_tasks"
4
+ require "rspec/core/rake_task"
5
+
6
+ RSpec::Core::RakeTask.new(:spec)
7
+
8
+ require "rubocop/rake_task"
9
+
10
+ RuboCop::RakeTask.new
11
+
12
+ task default: %i[spec rubocop]
@@ -0,0 +1,124 @@
1
+ module Text
2
+ module Gen
3
+ class Filter
4
+ class << self
5
+ def functions(result, filters)
6
+ return result if filters.nil? || filters.empty?
7
+
8
+ filters.each do |filter|
9
+ case filter["type"]
10
+ when "capitalize"
11
+ result = Result.from(text: result.text.capitalize, type: :function, result:)
12
+ when "downcase"
13
+ result = Result.from(text: result.text.downcase, type: :function, result:)
14
+ when "upcase"
15
+ result = Result.from(text: result.text.upcase, type: :function, result:)
16
+ when "titleize"
17
+ result = Result.from(text: Titleizer.titleize(result.text), type: :function, result:)
18
+ when "clear"
19
+ result = Result.from(text: result.text, type: :function, result:)
20
+ result.clear_meta(filter["key"], filter["value"])
21
+ result
22
+ when "meta"
23
+ result = Result.from(text: result.text, type: :function, result:)
24
+ result.merge_kv(filter["key"], filter["value"])
25
+ result
26
+ end
27
+ end
28
+
29
+ result
30
+ end
31
+
32
+ def filter_select(items, filters)
33
+ select_filters = filters_by_type(filters, "select")
34
+ return items if select_filters.empty?
35
+
36
+ items.select do |item|
37
+ select_filters.any? { |f| pass_select?(item["meta"], f["key"], f["value"]) }
38
+ end
39
+ end
40
+
41
+ def filter_reject(items, filters)
42
+ reject_filters = filters_by_type(filters, "reject")
43
+ return items if reject_filters.empty?
44
+
45
+ items.select do |item|
46
+ reject_filters.all? { |f| pass_reject?(item["meta"], f["key"], f["value"]) }
47
+ end
48
+ end
49
+
50
+ def result_select(result, filters)
51
+ match_filters = filters_by_type(filters, "match")
52
+ return result if match_filters.empty?
53
+ return result if match_filters.any? { |f| pass_select?(result.meta, f["key"], f["value"]) }
54
+
55
+ nil
56
+ end
57
+
58
+ def result_reject(result, filters)
59
+ exclude_filters = filters_by_type(filters, "exclude")
60
+ return result if exclude_filters.empty?
61
+ return result if exclude_filters.all? { |f| pass_reject?(result.meta, f["key"], f["value"]) }
62
+
63
+ nil
64
+ end
65
+
66
+ # Replace locale is used on an item; if the item is selected and has
67
+ # associated meta value of "locale" and the request is using that locale value
68
+ # then replace the item text with the value of the meta. If there is
69
+ # more than one value, select at random.
70
+ def replace_locale(meta, locale)
71
+ return if locale.nil?
72
+ return if meta.nil? || meta.empty?
73
+
74
+ meta[locale.downcase]&.sample
75
+ end
76
+
77
+ def pass_select?(meta, key, value)
78
+ return true if value == "*" && meta.key?(key)
79
+ return true if key == "*" && meta.values.any? { |arr| arr.include?(value) }
80
+
81
+ meta[key]&.include?(value)
82
+ end
83
+
84
+ def pass_reject?(meta, key, value)
85
+ return false if value == "*" && meta.key?(key)
86
+ return false if key == "*" && meta.values.any? { |arr| arr.include?(value) }
87
+
88
+ !meta[key]&.include?(value)
89
+ end
90
+
91
+ def separator(filters)
92
+ separator_filter = filter_by_type(filters, "separator")
93
+ return "" unless separator_filter
94
+ return separator_filter["value"] if separator_filter["key"] == "string"
95
+
96
+ case separator_filter["key"]
97
+ when "tab"
98
+ "\t"
99
+ when "space"
100
+ " "
101
+ when "newline"
102
+ "\n"
103
+ else
104
+ ""
105
+ end
106
+ end
107
+
108
+ def filter_by_type(filters, type)
109
+ return if filters.nil?
110
+ return if filters.empty?
111
+
112
+ filters.find { |f| f["type"] == type }
113
+ end
114
+
115
+ def filters_by_type(filters, type)
116
+ return [] if filters.nil?
117
+ return filters if filters.empty?
118
+
119
+ filters.select { |f| f["type"] == type }
120
+ end
121
+ end
122
+ end
123
+ end
124
+ end
@@ -0,0 +1,5 @@
1
+ module Text
2
+ module Gen
3
+ class FilterError < StandardError; end
4
+ end
5
+ end
@@ -0,0 +1,7 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Text
4
+ module Gen
5
+ class LookupError < StandardError; end
6
+ end
7
+ end
@@ -0,0 +1,5 @@
1
+ module Text
2
+ module Gen
3
+ class MaxAttemptsError < StandardError; end
4
+ end
5
+ end
@@ -0,0 +1,5 @@
1
+ module Text
2
+ module Gen
3
+ class MaxRecursionError < StandardError; end
4
+ end
5
+ end
@@ -0,0 +1,91 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Text
4
+ module Gen
5
+ # Result stores the generated text, value and metadata and context about
6
+ # how it was created
7
+ class Result
8
+ attr_reader :text, :type, :value, :multiplier, :meta, :components
9
+
10
+ def initialize(text:, type:, value: 0, multiplier: 1)
11
+ @text = text
12
+ @type = type.to_s
13
+ @value = [0, (value || 0).to_i].max
14
+ @multiplier = [1, (multiplier || 1).to_i].max
15
+ @meta = {}
16
+ @components = []
17
+ end
18
+
19
+ def to_h
20
+ {
21
+ text:,
22
+ type:,
23
+ value:,
24
+ multiplier:,
25
+ meta:,
26
+ components: components.map(&:to_h)
27
+ }
28
+ end
29
+
30
+ def merge_all_meta(results)
31
+ return unless results
32
+
33
+ results.each do |r|
34
+ r.meta.each { |k, v| merge_kv(k, v) }
35
+ end
36
+ end
37
+
38
+ def merge_meta(hsh)
39
+ return unless hsh
40
+
41
+ hsh.each { |k, v| merge_kv(k, v) }
42
+ end
43
+
44
+ def merge_kv(key, val)
45
+ key = key.to_s.downcase
46
+ arr = val.is_a?(Array) ? val : Array(val)
47
+ meta[key] = meta.key?(key) ? (meta[key] + arr).uniq : arr.dup
48
+ end
49
+
50
+ def clear_meta(key, val)
51
+ if key == "*" && val == "*"
52
+ @meta = {}
53
+ elsif key == "*"
54
+ @meta.each_value { |v| v.delete(val) }
55
+ elsif val == "*"
56
+ @meta.delete(key)
57
+ else
58
+ @meta[key]&.delete(val)
59
+ end
60
+ end
61
+
62
+ def to_s
63
+ @text
64
+ end
65
+
66
+ class << self
67
+ def from(text:, type:, result:, value: nil, multiplier: nil)
68
+ value ||= result.value
69
+ multiplier ||= result.multiplier
70
+ new(text:, type:, value:, multiplier:).tap do |s|
71
+ s.components.append(result)
72
+ s.merge_meta(result.meta)
73
+ end
74
+ end
75
+
76
+ def merge(results, separator, meta = {}, type: :sequence)
77
+ new(
78
+ text: results.map(&:text).join(separator),
79
+ type: type,
80
+ value: results.sum(&:value),
81
+ multiplier: results.reduce(1) { |acc, r| acc * r.multiplier }
82
+ ).tap do |result|
83
+ result.components.append(*results)
84
+ result.merge_all_meta(results)
85
+ result.merge_meta(meta)
86
+ end
87
+ end
88
+ end
89
+ end
90
+ end
91
+ end
@@ -0,0 +1,274 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "dice_nom_shim"
4
+ require "json"
5
+
6
+ module Text
7
+ module Gen
8
+ # ResultAccumulator handles accumulating results with attempt tracking
9
+ class ResultAccumulator
10
+ class << self
11
+ def accumulate(unique:, count:, max_attempts:, &block)
12
+ new(unique: unique, count: count, max_attempts: max_attempts).accumulate(&block)
13
+ end
14
+ end
15
+
16
+ def initialize(unique:, count:, max_attempts:)
17
+ @unique = unique
18
+ @count = count
19
+ @max_attempts = max_attempts
20
+ @results = unique ? {} : []
21
+ @attempts = max_attempts * count
22
+ end
23
+
24
+ def accumulate(&block)
25
+ while @results.size < @count
26
+ result = block.call
27
+ add_result(result) if result
28
+
29
+ @attempts -= 1
30
+ raise MaxAttemptsError if @attempts.zero?
31
+ end
32
+
33
+ @results.map { |_, v| v }
34
+ end
35
+
36
+ private
37
+
38
+ def add_result(result)
39
+ if @unique
40
+ @results[result.text] = result
41
+ else
42
+ @results << [result.text, result]
43
+ end
44
+ end
45
+ end
46
+
47
+ # AltLookup handles alternative filter lookups
48
+ class AltLookup
49
+ def initialize(request_filters)
50
+ @filters = {}
51
+ populate(request_filters)
52
+ end
53
+
54
+ def key?(key)
55
+ @filters.key?(key)
56
+ end
57
+
58
+ def [](key)
59
+ @filters[key]
60
+ end
61
+
62
+ private
63
+
64
+ def populate(request_filters)
65
+ request_filters.each do |f|
66
+ next unless f["type"] == "alt"
67
+
68
+ k = f["key"]
69
+ v = f["value"]
70
+ raise FilterError, "Invalid alt filter" if k.nil? || v.nil? || k.empty?
71
+
72
+ (@filters[k.to_s.downcase] ||= []) << v
73
+ end
74
+ end
75
+ end
76
+
77
+ # Runner generates results from the builder that is found with the given key.
78
+ class Runner
79
+ attr_reader :key, :locale, :lookup, :store, :max_attempts, :max_recursion
80
+
81
+ def initialize(
82
+ key:,
83
+ lookup:,
84
+ locale: nil,
85
+ unique: false,
86
+ max_recursion: 10,
87
+ max_attempts: 10,
88
+ request_filters: []
89
+ )
90
+ @key = key.to_s.downcase
91
+ @lookup = lookup
92
+ @locale = locale
93
+ @store = Store.new
94
+ @unique = unique
95
+ @request_filters = request_filters
96
+ @max_attempts = max_attempts
97
+ @max_recursion = max_recursion
98
+ @alt_lookup = AltLookup.new(request_filters)
99
+ end
100
+
101
+ def unique?
102
+ @unique
103
+ end
104
+
105
+ def run(count: 1)
106
+ builder = fetch_builder(key)
107
+
108
+ ResultAccumulator.accumulate(unique: unique?, count: count, max_attempts: max_attempts) do
109
+ run_builder(key, builder, @request_filters, 0)
110
+ end
111
+ end
112
+
113
+ def fetch_builder(key)
114
+ builder = store.find(key) || lookup.call(key)
115
+ store.add(key, builder)
116
+ builder
117
+ end
118
+
119
+ # A builder is hash with a key field, items, filters, and meta
120
+ def run_builder(key, builder, filters, depth)
121
+ depth += 1
122
+ raise MaxRecursionError if depth > max_recursion
123
+
124
+ alt_result = alt_result_for(key, builder)
125
+ return alt_result if alt_result
126
+
127
+ current_filters = merge_filters(builder, filters)
128
+ current_items = apply_item_filters(builder["items"], current_filters)
129
+
130
+ result = run_items(builder["strategy"], current_items, current_filters, builder["meta"], depth)
131
+ result.merge_meta(builder["meta"])
132
+ result = apply_result_function(result, current_filters)
133
+ apply_result_filters(result, current_filters)
134
+ end
135
+
136
+ def run_items(strategy, items, filters, meta, depth)
137
+ case strategy
138
+ when "sequence"
139
+ sep = Filter.separator(filters)
140
+ run_item_sequence(items, sep, meta, depth)
141
+ when "weighted"
142
+ run_weighted_items(items, meta, depth)
143
+ else
144
+ run_random_item(items, meta, depth)
145
+ end
146
+ end
147
+
148
+ def run_random_item(items, meta, depth)
149
+ result = run_item(items.sample, depth)
150
+ result.merge_meta(meta)
151
+ result
152
+ end
153
+
154
+ def run_item_sequence(items, filters, meta, depth)
155
+ results = items.map { |item| run_item(item, depth) }
156
+ Result.merge(results, filters, meta, type: :sequence)
157
+ end
158
+
159
+ def run_weighted_items(items, meta, depth)
160
+ total_weight = items.sum { |item| item.fetch("weight", 1).to_i }
161
+ rand_weight = rand(total_weight)
162
+ current_weight = 0
163
+ item = items.find do |item|
164
+ current_weight += item["weight"]
165
+ current_weight > rand_weight
166
+ end
167
+ result = run_item(item, depth)
168
+ result.merge_meta(meta)
169
+ result
170
+ end
171
+
172
+ def run_item(item, depth)
173
+ locale_result = locale_result_for(item)
174
+ return locale_result if locale_result
175
+
176
+ results = item["segments"].map { |seg| run_segment(seg, depth) }
177
+ sep = Filter.separator(item["filters"])
178
+ result = Result.merge(results, sep)
179
+ result.merge_meta(item["meta"])
180
+ result = apply_result_function(result, item["filters"])
181
+ apply_result_filters(result, item["filters"])
182
+ end
183
+
184
+ def run_segment(seg, depth)
185
+ case seg["type"]
186
+ when "dice"
187
+ run_dice_segment(seg)
188
+ when "number"
189
+ run_number_segment(seg)
190
+ when "reference"
191
+ run_reference_segment(seg, depth)
192
+ else
193
+ Result.new(text: seg["text"], value: seg["value"], type: :constant)
194
+ end
195
+ end
196
+
197
+ def run_dice_segment(seg)
198
+ rolled = DiceNomShim.roll(seg["text"])
199
+ parsed = JSON.parse(rolled)
200
+ result = parsed[0].dig("lhs", "total")
201
+ Result.new(text: result.to_s, multiplier: result, type: :dice)
202
+ end
203
+
204
+ def run_number_segment(seg)
205
+ num = seg["text"].to_i
206
+ Result.new(text: num.to_s, value: num, type: :number)
207
+ end
208
+
209
+ def run_reference_segment(seg, depth)
210
+ key = seg["text"]
211
+ run_builder(key, fetch_builder(key), seg.fetch("filters", []), depth)
212
+ end
213
+
214
+ def apply_result_filters(result, filters)
215
+ result = Filter.result_select(result, filters)
216
+ result = Filter.result_reject(result, filters) if result
217
+ result
218
+ end
219
+
220
+ def apply_result_function(result, filters)
221
+ Filter.functions(result, filters)
222
+ end
223
+
224
+ def merge_filters(builder, filters)
225
+ builder.key?("filters") ? builder["filters"] + filters : filters
226
+ end
227
+
228
+ def apply_item_filters(items, filters)
229
+ items = Filter.filter_select(items, filters)
230
+ items = Filter.filter_reject(items, filters)
231
+ raise FilterError if items.empty?
232
+
233
+ items
234
+ end
235
+
236
+ def alt_result_for(key, builder)
237
+ return nil unless @alt_lookup.key?(builder["key"])
238
+
239
+ Result.new(text: @alt_lookup[key], type: :alt, meta: builder["meta"])
240
+ end
241
+
242
+ def locale_result_for(item)
243
+ text = Filter.replace_locale(item["meta"], locale)
244
+ return nil unless text
245
+
246
+ Result.new(text:, type: :locale, value: item["value"], multiplier: item["multiplier"])
247
+ end
248
+
249
+ def to_h
250
+ {
251
+ "key" => key,
252
+ "request_filters" => request_filters,
253
+ "request_meta" => request_meta,
254
+ "store" => store.to_h
255
+ }
256
+ end
257
+
258
+ class << self
259
+ def from_hash(hash)
260
+ runner = Runner.new(
261
+ key: hash["key"],
262
+ request_filters: hash.fetch("request_filters", [])
263
+ )
264
+
265
+ hash.fetch("store", {}).each do |k, b|
266
+ runner.store.add(k, b)
267
+ end
268
+
269
+ runner
270
+ end
271
+ end
272
+ end
273
+ end
274
+ end
@@ -0,0 +1,25 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Text
4
+ module Gen
5
+ # Store is a local cache of a builder that is persistent per store
6
+ # to save time on database lookups or transformations.
7
+ class Store
8
+ def initialize
9
+ @store = {}
10
+ end
11
+
12
+ def find(key)
13
+ @store[key.to_s.downcase]
14
+ end
15
+
16
+ def add(key, builder)
17
+ @store[key.to_s.downcase] = builder
18
+ end
19
+
20
+ def to_h
21
+ @store
22
+ end
23
+ end
24
+ end
25
+ end
@@ -0,0 +1,20 @@
1
+ module Text
2
+ module Gen
3
+ class Titleizer
4
+ SKIP_WORDS = Set.new(%w[a an and as at but by for if in of on or the to v via vs])
5
+
6
+ class << self
7
+ def titleize(str)
8
+ arr = str.split(/\s+/)
9
+ idx = 0
10
+ len = arr.length
11
+ while idx < len
12
+ arr[idx] = arr[idx].capitalize if idx == 0 || !SKIP_WORDS.include?(arr[idx])
13
+ idx += 1
14
+ end
15
+ arr.join(" ")
16
+ end
17
+ end
18
+ end
19
+ end
20
+ end
@@ -0,0 +1,7 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Text
4
+ module Gen
5
+ VERSION = "0.1.0"
6
+ end
7
+ end
data/lib/text/gen.rb ADDED
@@ -0,0 +1,20 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative "gen/version"
4
+ require_relative "gen/filter_error"
5
+ require_relative "gen/lookup_error"
6
+ require_relative "gen/max_attempts_error"
7
+ require_relative "gen/max_recursion_error"
8
+
9
+ require_relative "gen/titleizer"
10
+ require_relative "gen/result"
11
+ require_relative "gen/filter"
12
+ require_relative "gen/store"
13
+ require_relative "gen/runner"
14
+
15
+ module Text
16
+ module Gen
17
+ class Error < StandardError; end
18
+ # Your code goes here...
19
+ end
20
+ end
data/sig/text/gen.rbs ADDED
@@ -0,0 +1,6 @@
1
+ module Text
2
+ module Gen
3
+ VERSION: String
4
+ # See the writing guide of rbs: https://github.com/ruby/rbs#guides
5
+ end
6
+ end
metadata ADDED
@@ -0,0 +1,79 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: text-gen
3
+ version: !ruby/object:Gem::Version
4
+ version: 0.1.0
5
+ platform: ruby
6
+ authors:
7
+ - G Palmer
8
+ bindir: exe
9
+ cert_chain: []
10
+ date: 1980-01-02 00:00:00.000000000 Z
11
+ dependencies:
12
+ - !ruby/object:Gem::Dependency
13
+ name: dice_nom_shim
14
+ requirement: !ruby/object:Gem::Requirement
15
+ requirements:
16
+ - - "~>"
17
+ - !ruby/object:Gem::Version
18
+ version: 0.5.0
19
+ type: :runtime
20
+ prerelease: false
21
+ version_requirements: !ruby/object:Gem::Requirement
22
+ requirements:
23
+ - - "~>"
24
+ - !ruby/object:Gem::Version
25
+ version: 0.5.0
26
+ description: |
27
+ Library to build random text strings from rules defined as ruby hashes.
28
+ Rules consist of Builders, which have Items which are componsed of Segments.
29
+ Generated text can be modified with filters.
30
+ email:
31
+ - palmergs@gmail.com
32
+ executables: []
33
+ extensions: []
34
+ extra_rdoc_files: []
35
+ files:
36
+ - CHANGELOG.md
37
+ - CODE_OF_CONDUCT.md
38
+ - LICENSE.txt
39
+ - README.md
40
+ - Rakefile
41
+ - lib/text/gen.rb
42
+ - lib/text/gen/filter.rb
43
+ - lib/text/gen/filter_error.rb
44
+ - lib/text/gen/lookup_error.rb
45
+ - lib/text/gen/max_attempts_error.rb
46
+ - lib/text/gen/max_recursion_error.rb
47
+ - lib/text/gen/result.rb
48
+ - lib/text/gen/runner.rb
49
+ - lib/text/gen/store.rb
50
+ - lib/text/gen/titleizer.rb
51
+ - lib/text/gen/version.rb
52
+ - sig/text/gen.rbs
53
+ homepage: https://github.com/palmergs/text-gen
54
+ licenses:
55
+ - MIT
56
+ metadata:
57
+ allowed_push_host: https://rubygems.org
58
+ rubygems_mfa_required: 'true'
59
+ homepage_uri: https://github.com/palmergs/text-gen
60
+ source_code_uri: https://github.com/palmergs/text-gen
61
+ changelog_uri: https://github.com/palmergs/text-gen/blob/release/CHANGELOG.md
62
+ rdoc_options: []
63
+ require_paths:
64
+ - lib
65
+ required_ruby_version: !ruby/object:Gem::Requirement
66
+ requirements:
67
+ - - ">="
68
+ - !ruby/object:Gem::Version
69
+ version: 3.2.0
70
+ required_rubygems_version: !ruby/object:Gem::Requirement
71
+ requirements:
72
+ - - ">="
73
+ - !ruby/object:Gem::Version
74
+ version: '0'
75
+ requirements: []
76
+ rubygems_version: 3.6.9
77
+ specification_version: 4
78
+ summary: Build random text strings from rules
79
+ test_files: []