ladl 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.
@@ -0,0 +1,282 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Ladl
4
+ module Runtime
5
+ # The LADL labeling engine: evaluates a resolved label style against
6
+ # a content tree, producing a Ladl::Label per labeled element.
7
+ #
8
+ # The engine implements the MN 112 algorithm to resolve the label
9
+ # for a content element:
10
+ #
11
+ # 1. Walk the content tree depth-first, maintaining a stack of
12
+ # label context instances (the context tree, instantiated) and a
13
+ # stack of labeled element entries (for `%pn`/`%parent`
14
+ # resolution).
15
+ # 2. For each element, find the labeller bound to the nearest
16
+ # enclosing context instance that can label the element type.
17
+ # 3. Instantiate the label context the element opens, per the
18
+ # profile (a context whose parent is the labeller's context, or
19
+ # one named after the element type).
20
+ # 4. Increment the labeller's counter within the context instance
21
+ # the labeller is bound to, scoped by the parent element when the
22
+ # labeller has a parent labeller.
23
+ # 5. Select the label template: the first whose
24
+ # LabelContextCondition evaluates to true against the total count
25
+ # of similar elements in the same context (MN 112 conditional
26
+ # templates); fall back to the first unconditional template.
27
+ # 6. Render the template pattern with string interpolation.
28
+ #
29
+ # The walk runs first (planning + counting), then labels are
30
+ # rendered, so conditional templates see final sibling counts.
31
+ class Engine
32
+ # A label context instance: the runtime instantiation of a
33
+ # LabelContext definition. Counters are keyed by
34
+ # [frame path, labeller name, parent scope].
35
+ Frame = Struct.new(:instance_name, :path, :counters, :anchor_entry,
36
+ keyword_init: true)
37
+
38
+ # A labeled element planned during the walk.
39
+ Entry = Struct.new(:element, :type, :labeller, :labeller_name, :frame,
40
+ :key, :position, :raw_value, :parent_hier, :parent_frame,
41
+ :hierarchical, :local, :global,
42
+ keyword_init: true)
43
+
44
+ attr_reader :result, :resolved
45
+
46
+ # @param resolved [Runtime::Resolver, Ladl::Profile] a resolved
47
+ # label style, or a profile to resolve
48
+ def initialize(resolved)
49
+ @resolved = case resolved
50
+ when Runtime::Resolver
51
+ resolved
52
+ when Ladl::Profile
53
+ Runtime::Resolver.new(resolved)
54
+ else
55
+ raise Ladl::Error,
56
+ "engine requires a Ladl::Profile or Runtime::Resolver, " \
57
+ "got #{resolved.class}"
58
+ end
59
+ @frames = []
60
+ @entries = []
61
+ @plan = []
62
+ @totals = {}
63
+ @frame_seq = 0
64
+ @result = Result.new
65
+ end
66
+
67
+ # Labels the content tree rooted at `root` and returns the
68
+ # Ladl::Runtime::Result.
69
+ def label(root)
70
+ walk(root)
71
+ render
72
+ @result
73
+ end
74
+ alias label_document label
75
+
76
+ private
77
+
78
+ def walk(element)
79
+ type = element.type.to_s
80
+ labeller, counter_frame = resolve_labeller(type)
81
+ frame = open_frame(type, labeller, element)
82
+ entry = plan_element(element, labeller, counter_frame) if labeller
83
+ frame.anchor_entry = entry if frame
84
+ children_of(element).each { |child| walk(child) }
85
+ @entries.pop if entry
86
+ @frames.pop if frame
87
+ end
88
+
89
+ def children_of(element)
90
+ return [] unless element.respond_to?(:children)
91
+
92
+ Array(element.children)
93
+ end
94
+
95
+ # MN 112 algorithm step 2: the labeller bound to the nearest
96
+ # enclosing context instance that can label this element type.
97
+ # Returns [labeller, frame the labeller's counters live in].
98
+ def resolve_labeller(type)
99
+ @frames.reverse_each do |frame|
100
+ labeller = @resolved.labeller_for_context(frame.instance_name, type)
101
+ return [labeller, frame] if labeller
102
+ end
103
+ [nil, nil]
104
+ end
105
+
106
+ # MN 112 algorithm step 3: the label context instance this element
107
+ # opens, if any. Preference order: a child context of the
108
+ # element's labeller context matching the element type; a unique
109
+ # child context of the element's labeller context not already
110
+ # active; a context named after the element type.
111
+ def open_frame(type, labeller, element)
112
+ candidate = nil
113
+ if labeller
114
+ child_contexts = @resolved.contexts_with_parent(labeller.context)
115
+ named = child_contexts.select do |name|
116
+ @resolved.context_name(name) == type
117
+ end
118
+ if named.size == 1
119
+ candidate = named.first
120
+ elsif child_contexts.size == 1 && !active?(child_contexts.first)
121
+ candidate = child_contexts.first
122
+ end
123
+ end
124
+ candidate ||= top_level_named(type)
125
+ return nil unless candidate
126
+
127
+ @frame_seq += 1
128
+ frame = Frame.new(
129
+ instance_name: candidate,
130
+ path: "#{@frames.last ? @frames.last.path : ""}/#{candidate}[#{@frame_seq}]",
131
+ counters: Hash.new(0),
132
+ )
133
+ @frames.push(frame)
134
+ frame
135
+ end
136
+
137
+ def active?(instance_name)
138
+ @frames.any? { |f| f.instance_name == instance_name }
139
+ end
140
+
141
+ def top_level_named(type)
142
+ named = @resolved.contexts_named(type)
143
+ named.size == 1 ? named.first : nil
144
+ end
145
+
146
+ def plan_element(element, labeller, counter_frame)
147
+ parent = find_parent_entry(labeller)
148
+ parent_hier = parent&.hierarchical
149
+ position = increment_counter(counter_frame, labeller, parent_hier)
150
+ raw = sequence_raw(labeller, position)
151
+ entry = Entry.new(
152
+ element: element,
153
+ type: element.type.to_s,
154
+ labeller: labeller,
155
+ labeller_name: @resolved.instance_name_of(labeller),
156
+ frame: counter_frame,
157
+ key: [counter_frame.path, @resolved.instance_name_of(labeller),
158
+ parent_hier.to_s],
159
+ position: position,
160
+ raw_value: raw,
161
+ parent_hier: parent_hier,
162
+ parent_frame: counter_frame,
163
+ hierarchical: join_hierarchical(parent_hier, raw),
164
+ )
165
+ @entries.push(entry)
166
+ @plan << entry
167
+ entry
168
+ end
169
+
170
+ # The nearest enclosing labeled element that supplies the `%pn`
171
+ # value and the hierarchical counter scope for this labeller:
172
+ # the nearest entry labeled by a labeller in this labeller's
173
+ # self-inclusive ancestor chain (the enclosing subclause for
174
+ # 1.2.1, the enclosing annex for Figure A.1, the containing list
175
+ # item for a nested list item). Falls back to the nearest entry
176
+ # of the parent labeller's element type (e.g. an enclosing figure
177
+ # labeled by the annex figure labeller for a subfigure).
178
+ def find_parent_entry(labeller)
179
+ parent_name = labeller.parent
180
+ return nil if parent_name.nil? || parent_name.empty?
181
+
182
+ parent_labeller = @resolved.profile.labeller(parent_name)
183
+ unless parent_labeller
184
+ raise Ladl::ResolutionError,
185
+ "labeller #{@resolved.instance_name_of(labeller).inspect} " \
186
+ "references undefined parent labeller #{parent_name.inspect}"
187
+ end
188
+ chain = @resolved.ancestor_chain(@resolved.instance_name_of(labeller))
189
+ @entries.reverse_each do |entry|
190
+ return entry if chain.include?(entry.labeller_name)
191
+ end
192
+ @entries.reverse_each do |entry|
193
+ return entry if entry.type == parent_labeller.type
194
+ end
195
+ nil
196
+ end
197
+
198
+ def increment_counter(frame, labeller, parent_hier)
199
+ key = [frame.path, @resolved.instance_name_of(labeller), parent_hier.to_s]
200
+ count = frame.counters[key] + 1
201
+ frame.counters[key] = count
202
+ @totals[key] = count
203
+ count
204
+ end
205
+
206
+ def sequence_raw(labeller, position)
207
+ return if labeller.sequence.nil? || labeller.sequence.empty?
208
+
209
+ @resolved.sequence_value(labeller.sequence, position)
210
+ end
211
+
212
+ def join_hierarchical(parent_hier, raw)
213
+ return parent_hier if parent_hier && raw.nil?
214
+ return raw if parent_hier.nil?
215
+
216
+ "#{parent_hier}.#{raw}"
217
+ end
218
+
219
+ # MN 112 algorithm step 5: select the first template whose
220
+ # condition evaluates to true; if no condition evaluates to true,
221
+ # select the first template without a condition, or the first
222
+ # template if all have conditions.
223
+ def select_template(templates, total)
224
+ templates.find { |template| template.condition&.evaluate(total) } ||
225
+ templates.find { |template| template.condition.nil? } ||
226
+ templates.first
227
+ end
228
+
229
+ def render
230
+ @plan.each do |entry|
231
+ total = @totals.fetch(entry.key, 1)
232
+ labeller = entry.labeller
233
+ local_template = select_template(
234
+ Array(labeller.template), total
235
+ )
236
+ unless local_template
237
+ raise Ladl::ResolutionError,
238
+ "labeller #{entry.labeller_name.inspect} has no label template"
239
+ end
240
+ bindings = base_bindings(entry)
241
+ entry.local = Renderer.render(
242
+ local_template.pattern, bindings.merge(pattern: local_template.pattern)
243
+ )
244
+ globals = Array(labeller.global_template)
245
+ entry.global = if globals.empty?
246
+ entry.local
247
+ else
248
+ global_template = select_template(globals, total)
249
+ Renderer.render(
250
+ global_template.pattern,
251
+ bindings.merge(pattern: global_template.pattern, self: entry.local),
252
+ )
253
+ end
254
+ @result.add(build_label(entry, labeller))
255
+ end
256
+ end
257
+
258
+ def base_bindings(entry)
259
+ anchor = entry.parent_frame&.anchor_entry
260
+ {
261
+ n: entry.raw_value,
262
+ pn: entry.parent_hier,
263
+ parent: anchor&.global,
264
+ }
265
+ end
266
+
267
+ def build_label(entry, labeller)
268
+ label = Ladl::Label.new(
269
+ value: entry.local,
270
+ global_value: entry.global,
271
+ hierarchical: entry.hierarchical,
272
+ sequence_value: entry.raw_value,
273
+ position: entry.position,
274
+ labeller_id: labeller.id,
275
+ content_element: entry.element.respond_to?(:id) ? entry.element.id : nil,
276
+ )
277
+ label.element = entry.element
278
+ label
279
+ end
280
+ end
281
+ end
282
+ end
@@ -0,0 +1,49 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Ladl
4
+ module Runtime
5
+ # MN 112 "string interpolation" — substitutes variable placeholders
6
+ # in a label template pattern with actual values to construct a
7
+ # rendered label.
8
+ #
9
+ # Supported placeholders:
10
+ #
11
+ # * `%n` — the labeller value (sequence value at this position)
12
+ # * `%pn` — the parent labeller value (hierarchical path of the
13
+ # nearest enclosing parent-labeled element)
14
+ # * `%parent` — the rendered global label of the parent context
15
+ # element
16
+ # * `%self` — the rendered local label of the element itself
17
+ module Renderer
18
+ PLACEHOLDER = /%pn|%parent|%self|%n/.freeze
19
+
20
+ module_function
21
+
22
+ # Renders `pattern` with the given bindings. A `%pn` placeholder in
23
+ # the pattern with no parent value bound is a profile error.
24
+ def render(pattern, bindings)
25
+ pattern.to_s.gsub(PLACEHOLDER) do |placeholder|
26
+ case placeholder
27
+ when "%n"
28
+ text(bindings[:n], placeholder, bindings)
29
+ when "%pn"
30
+ text(bindings[:pn], placeholder, bindings)
31
+ when "%parent"
32
+ text(bindings[:parent], placeholder, bindings)
33
+ when "%self"
34
+ text(bindings[:self], placeholder, bindings)
35
+ end
36
+ end
37
+ end
38
+
39
+ def text(value, placeholder, bindings)
40
+ return value.to_s unless value.nil?
41
+ return "" if placeholder == "%parent" || placeholder == "%self"
42
+
43
+ raise Ladl::ResolutionError,
44
+ "template #{bindings[:pattern].inspect} uses #{placeholder} " \
45
+ "but the labeller has no parent labeller bound for this element"
46
+ end
47
+ end
48
+ end
49
+ end
@@ -0,0 +1,175 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Ladl
4
+ module Runtime
5
+ # Wires a loaded Ladl::Profile into the indexes the engine needs:
6
+ # labellers by context instance and element type, context instances
7
+ # by name attribute and parent relation, sequence resolution, and
8
+ # the labeller-tree descendant index used for `%pn` resolution.
9
+ class Resolver
10
+ attr_reader :profile
11
+
12
+ def initialize(profile)
13
+ @profile = profile
14
+ validate_style_references
15
+ @labeller_names = {}
16
+ @profile.labeller_names.each do |name|
17
+ @labeller_names[@profile.labeller(name)] = name
18
+ end
19
+ @labellers_by_context = build_labeller_index
20
+ @descendants = build_descendants
21
+ @context_names = {}
22
+ @profile.context_names.each do |name|
23
+ context = @profile.context(name)
24
+ @context_names[name] = context.name if context.name
25
+ end
26
+ end
27
+
28
+ # The labeller bound to `context_instance_name` (a context
29
+ # instance name, e.g. "ClauseContext") that labels elements of
30
+ # `type`, or nil.
31
+ def labeller_for_context(context_instance_name, type)
32
+ @labellers_by_context.dig(context_instance_name, type)
33
+ end
34
+
35
+ # The `name` attribute of the context instance with the given
36
+ # instance name (e.g. "ClauseContext" -> "clause").
37
+ def context_name(instance_name)
38
+ @context_names[instance_name]
39
+ end
40
+
41
+ # Instance names of contexts whose `parent` is the given context
42
+ # instance name.
43
+ def contexts_with_parent(instance_name)
44
+ @profile.context_names.select do |name|
45
+ @profile.context(name).parent == instance_name
46
+ end
47
+ end
48
+
49
+ # Instance names of contexts whose `name` attribute equals the
50
+ # given element type (e.g. "clause" -> ["ClauseContext"]).
51
+ def contexts_named(type)
52
+ @profile.context_names.select do |name|
53
+ @context_names[name] == type
54
+ end
55
+ end
56
+
57
+ # Sequence value for the given sequence reference (instance name)
58
+ # at the given 1-based position; nil when the reference is blank.
59
+ def sequence_value(sequence_name, position)
60
+ return if sequence_name.nil? || sequence_name.empty?
61
+
62
+ sequence = @profile.sequence(sequence_name) || Sequences::Registry.lookup(sequence_name)
63
+ unless sequence
64
+ raise Ladl::ResolutionError,
65
+ "undefined sequence: #{sequence_name.inspect}"
66
+ end
67
+ Sequences.value_for(sequence, position, lookup: method(:lookup_sequence))
68
+ end
69
+
70
+ # True when `labeller_name` is a strict descendant of
71
+ # `ancestor_name` in the labeller tree.
72
+ def descendant_labeller?(ancestor_name, labeller_name)
73
+ @descendants[ancestor_name].include?(labeller_name)
74
+ end
75
+
76
+ # The self-inclusive ancestor chain of the given labeller instance
77
+ # name: the labeller itself followed by its parent, grandparent,
78
+ # ... in the labeller tree.
79
+ def ancestor_chain(labeller_name)
80
+ chain = [labeller_name]
81
+ seen = { labeller_name => true }
82
+ current = labeller_name
83
+ while (parent = @profile.labeller(current)&.parent)
84
+ break if seen.key?(parent)
85
+
86
+ chain << parent
87
+ seen[parent] = true
88
+ current = parent
89
+ end
90
+ chain
91
+ end
92
+
93
+ # The instance name of a labeller model within the profile.
94
+ def instance_name_of(labeller)
95
+ @labeller_names[labeller]
96
+ end
97
+
98
+ # The parent labeller instance name of the given labeller, or nil.
99
+ def parent_labeller_name(labeller)
100
+ labeller.parent
101
+ end
102
+
103
+ def lookup_sequence(name)
104
+ @profile.sequence(name) || Sequences::Registry.lookup(name)
105
+ end
106
+
107
+ private
108
+
109
+ def validate_style_references
110
+ missing = []
111
+ Array(@profile.style.labellers).each do |ref|
112
+ id = ref.start_with?("id:") ? ref[3..] : ref
113
+ missing << ref unless @profile.labeller_by_id(id) || @profile.labeller(ref)
114
+ end
115
+ Array(@profile.style.contexts).each do |ref|
116
+ missing << ref unless @profile.context(ref)
117
+ end
118
+ Array(@profile.style.templates).each do |ref|
119
+ missing << ref unless @profile.template(ref)
120
+ end
121
+ Array(@profile.style.sequences).each do |ref|
122
+ next if @profile.sequence(ref) || Sequences::Registry.lookup(ref)
123
+
124
+ missing << ref
125
+ end
126
+ unless missing.empty?
127
+ raise Ladl::ResolutionError,
128
+ "label style #{@profile.style.name.inspect} references " \
129
+ "undefined instances: #{missing.join(", ")}"
130
+ end
131
+ end
132
+
133
+ def build_labeller_index
134
+ index = Hash.new { |h, k| h[k] = {} }
135
+ @profile.labeller_names.each do |name|
136
+ labeller = @profile.labeller(name)
137
+ context = labeller.context
138
+ unless context
139
+ raise Ladl::ResolutionError,
140
+ "labeller #{name.inspect} declares no context"
141
+ end
142
+ unless @profile.context(context)
143
+ raise Ladl::ResolutionError,
144
+ "labeller #{name.inspect} references undefined context " \
145
+ "#{context.inspect}"
146
+ end
147
+ index[context][labeller.type] = labeller
148
+ end
149
+ index
150
+ end
151
+
152
+ def build_descendants
153
+ children = Hash.new { |h, k| h[k] = [] }
154
+ @profile.labeller_names.each do |name|
155
+ labeller = @profile.labeller(name)
156
+ children[labeller.parent] << name if labeller.parent
157
+ end
158
+ descendants = Hash.new { |h, k| h[k] = [] }
159
+ @profile.labeller_names.each do |name|
160
+ collect_descendants(name, children, descendants[name])
161
+ end
162
+ descendants
163
+ end
164
+
165
+ def collect_descendants(name, children, into)
166
+ children[name].each do |child|
167
+ into << child
168
+ collect_descendants(child, children, into)
169
+ end
170
+ into.uniq!
171
+ into
172
+ end
173
+ end
174
+ end
175
+ end
@@ -0,0 +1,61 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Ladl
4
+ module Runtime
5
+ # The output of a labeling run: the Ladl::Label assigned to each
6
+ # content element, in document order, with lookup by element
7
+ # identity.
8
+ class Result
9
+ include Enumerable
10
+
11
+ def initialize
12
+ @labels = []
13
+ @by_element = {}.compare_by_identity
14
+ end
15
+
16
+ def add(label)
17
+ @labels << label
18
+ @by_element[label.element] = label if label.element
19
+ label
20
+ end
21
+
22
+ def each(&block)
23
+ @labels.each(&block)
24
+ end
25
+
26
+ def size
27
+ @labels.size
28
+ end
29
+ alias length size
30
+
31
+ def empty?
32
+ @labels.empty?
33
+ end
34
+
35
+ # The label for the given content element, or nil.
36
+ def label_for(element)
37
+ @by_element[element]
38
+ end
39
+
40
+ # The rendered local label for the given content element, or nil.
41
+ def local_for(element)
42
+ label = @by_element[element]
43
+ label&.value
44
+ end
45
+
46
+ # The rendered global label for the given content element, or nil.
47
+ def global_for(element)
48
+ label = @by_element[element]
49
+ label&.global_value
50
+ end
51
+
52
+ # Labels keyed by the content element id (elements without an id
53
+ # are omitted).
54
+ def labels_by_element_id
55
+ @labels.each_with_object({}) do |label, hash|
56
+ hash[label.element.id] = label if label.element && label.element.id
57
+ end
58
+ end
59
+ end
60
+ end
61
+ end
@@ -0,0 +1,10 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Ladl
4
+ module Runtime
5
+ autoload :Resolver, "ladl/runtime/resolver"
6
+ autoload :Engine, "ladl/runtime/engine"
7
+ autoload :Renderer, "ladl/runtime/renderer"
8
+ autoload :Result, "ladl/runtime/result"
9
+ end
10
+ end
@@ -0,0 +1,104 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Ladl
4
+ module Sequences
5
+ # Labeling formats: renders a 1-based numeric value in a particular
6
+ # alphanumeric system (MN 112 "labeling format").
7
+ module Formatters
8
+ ROMAN_PAIRS = [
9
+ [1000, "M"], [900, "CM"], [500, "D"], [400, "CD"], [100, "C"],
10
+ [90, "XC"], [50, "L"], [40, "XL"], [10, "X"], [9, "IX"],
11
+ [5, "V"], [4, "IV"], [1, "I"],
12
+ ].freeze
13
+
14
+ UNITS = {
15
+ "chinese" => %w[零 一 二 三 四 五 六 七 八 九],
16
+ "japanese" => %w[零 一 二 三 四 五 六 七 八 九],
17
+ "korean" => %w[영 일 이 삼 사 오 육 칠 팔 구],
18
+ }.freeze
19
+ SMALL_TEN = { "chinese" => "十", "japanese" => "十", "korean" => "십" }.freeze
20
+ SMALL_HUNDRED = { "chinese" => "百", "japanese" => "百", "korean" => "백" }.freeze
21
+ SMALL_THOUSAND = { "chinese" => "千", "japanese" => "千", "korean" => "천" }.freeze
22
+
23
+ module_function
24
+
25
+ # Renders the 1-based integer `number` in the given format.
26
+ #
27
+ # @param format [String] decimal, roman_upper, roman_lower,
28
+ # alpha_upper, alpha_lower, arabic_indic, chinese, japanese,
29
+ # korean
30
+ # @param number [Integer] a positive 1-based value
31
+ # @raise [Ladl::Error] on unknown format or non-positive value
32
+ def format(format, number)
33
+ raise Ladl::Error, "sequence value must be positive, got #{number}" if number.to_i < 1
34
+
35
+ case format
36
+ when "decimal" then number.to_s
37
+ when "roman_upper" then roman(number)
38
+ when "roman_lower" then roman(number).downcase
39
+ when "alpha_upper" then alpha(number)
40
+ when "alpha_lower" then alpha(number).downcase
41
+ when "arabic_indic" then arabic_indic(number)
42
+ when "chinese", "japanese", "korean" then east_asian(format, number)
43
+ else
44
+ raise Ladl::Error, "unknown labeling format: #{format.inspect}"
45
+ end
46
+ end
47
+
48
+ def roman(number)
49
+ result = +""
50
+ n = number
51
+ ROMAN_PAIRS.each do |value, letters|
52
+ while n >= value
53
+ result << letters
54
+ n -= value
55
+ end
56
+ end
57
+ result
58
+ end
59
+
60
+ # Spreadsheet-style letters: 1 -> A ... 26 -> Z, 27 -> AA.
61
+ def alpha(number)
62
+ Ladl::Sequences.digits(number, 26)
63
+ .map { |d| (64 + d).chr }
64
+ .join
65
+ end
66
+
67
+ def arabic_indic(number)
68
+ number.to_s.tr("0123456789", "٠١٢٣٤٥٦٧٨٩")
69
+ end
70
+
71
+ # East-Asian numerals up to 9999: compound tens, hundreds and
72
+ # thousands (十, 百, 千 / 십, 백, 천). The leading unit is dropped
73
+ # before the tens marker only (十, not 一十), while hundreds and
74
+ # thousands keep the unit (一百, 一千) per formal CJK numbering.
75
+ # Internal zeros are not marked (108 -> 一百八), matching
76
+ # document-numbering practice.
77
+ def east_asian(format, number)
78
+ units = UNITS.fetch(format)
79
+ thousands, rest_thousands = number.divmod(1000)
80
+ hundreds, rest_hundreds = rest_thousands.divmod(100)
81
+ tens, ones = rest_hundreds.divmod(10)
82
+
83
+ out = +""
84
+ out << compound(units, thousands, SMALL_THOUSAND.fetch(format),
85
+ drop_single_unit: false) if thousands.positive?
86
+ out << compound(units, hundreds, SMALL_HUNDRED.fetch(format),
87
+ drop_single_unit: false) if hundreds.positive?
88
+ out << compound(units, tens, SMALL_TEN.fetch(format),
89
+ drop_single_unit: true) if tens.positive?
90
+ out << units[ones] if ones.positive?
91
+ out
92
+ end
93
+
94
+ def compound(units, count, marker, drop_single_unit: true)
95
+ prefix = if count == 1 && drop_single_unit
96
+ ""
97
+ else
98
+ units[count]
99
+ end
100
+ "#{prefix}#{marker}"
101
+ end
102
+ end
103
+ end
104
+ end