hbl_text 0.1.11

Sign up to get free protection for your applications and to get access to all the features.
checksums.yaml ADDED
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA1:
3
+ metadata.gz: 720ee531deea1db9d9027e7eba8b8421a6c5b92f
4
+ data.tar.gz: 77f7414c3615964194cf4192f8fa9661d2108896
5
+ SHA512:
6
+ metadata.gz: a76bf53d52f7e5a847567fd5188e9c6aa4b2065b06cb30aeea852086116f254362cdb0df55f4d2bcc048b3147f96c6e4f5c4c6217a4926c2096689b614bd0a88
7
+ data.tar.gz: f8fae623ac1247479d2cf832ea8af17e5a8029282e5e5830d8b4a0a18df44904ae88b4aa79c8655ff7da94d4385b95223b00ec2817f699839915bd66fb331501
data/.gitignore ADDED
@@ -0,0 +1,8 @@
1
+ /.bundle/
2
+ /.yardoc
3
+ /_yardoc/
4
+ /coverage/
5
+ /doc/
6
+ /pkg/
7
+ /spec/reports/
8
+ /tmp/
@@ -0,0 +1,84 @@
1
+ # Contributor Covenant Code of Conduct
2
+
3
+ ## Our Pledge
4
+
5
+ We as members, contributors, and leaders pledge to make participation in our community a harassment-free experience for everyone, regardless of age, body size, visible or invisible disability, ethnicity, sex characteristics, gender identity and expression, level of experience, education, socio-economic status, nationality, personal appearance, race, religion, or sexual identity and orientation.
6
+
7
+ We pledge to act and interact in ways that contribute to an open, welcoming, diverse, inclusive, and healthy community.
8
+
9
+ ## Our Standards
10
+
11
+ Examples of behavior that contributes to a positive environment for our community include:
12
+
13
+ * Demonstrating empathy and kindness toward other people
14
+ * Being respectful of differing opinions, viewpoints, and experiences
15
+ * Giving and gracefully accepting constructive feedback
16
+ * Accepting responsibility and apologizing to those affected by our mistakes, and learning from the experience
17
+ * Focusing on what is best not just for us as individuals, but for the overall community
18
+
19
+ Examples of unacceptable behavior include:
20
+
21
+ * The use of sexualized language or imagery, and sexual attention or
22
+ advances of any kind
23
+ * Trolling, insulting or derogatory comments, and personal or political attacks
24
+ * Public or private harassment
25
+ * Publishing others' private information, such as a physical or email
26
+ address, without their explicit permission
27
+ * Other conduct which could reasonably be considered inappropriate in a
28
+ professional setting
29
+
30
+ ## Enforcement Responsibilities
31
+
32
+ Community leaders are responsible for clarifying and enforcing our standards of acceptable behavior and will take appropriate and fair corrective action in response to any behavior that they deem inappropriate, threatening, offensive, or harmful.
33
+
34
+ Community leaders have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct, and will communicate reasons for moderation decisions when appropriate.
35
+
36
+ ## Scope
37
+
38
+ This Code of Conduct applies within all community spaces, and also applies when an individual is officially representing the community in public spaces. Examples of representing our community include using an official e-mail address, posting via an official social media account, or acting as an appointed representative at an online or offline event.
39
+
40
+ ## Enforcement
41
+
42
+ Instances of abusive, harassing, or otherwise unacceptable behavior may be reported to the community leaders responsible for enforcement at TODO: Write your email address. All complaints will be reviewed and investigated promptly and fairly.
43
+
44
+ All community leaders are obligated to respect the privacy and security of the reporter of any incident.
45
+
46
+ ## Enforcement Guidelines
47
+
48
+ Community leaders will follow these Community Impact Guidelines in determining the consequences for any action they deem in violation of this Code of Conduct:
49
+
50
+ ### 1. Correction
51
+
52
+ **Community Impact**: Use of inappropriate language or other behavior deemed unprofessional or unwelcome in the community.
53
+
54
+ **Consequence**: A private, written warning from community leaders, providing clarity around the nature of the violation and an explanation of why the behavior was inappropriate. A public apology may be requested.
55
+
56
+ ### 2. Warning
57
+
58
+ **Community Impact**: A violation through a single incident or series of actions.
59
+
60
+ **Consequence**: A warning with consequences for continued behavior. No interaction with the people involved, including unsolicited interaction with those enforcing the Code of Conduct, for a specified period of time. This includes avoiding interactions in community spaces as well as external channels like social media. Violating these terms may lead to a temporary or permanent ban.
61
+
62
+ ### 3. Temporary Ban
63
+
64
+ **Community Impact**: A serious violation of community standards, including sustained inappropriate behavior.
65
+
66
+ **Consequence**: A temporary ban from any sort of interaction or public communication with the community for a specified period of time. No public or private interaction with the people involved, including unsolicited interaction with those enforcing the Code of Conduct, is allowed during this period. Violating these terms may lead to a permanent ban.
67
+
68
+ ### 4. Permanent Ban
69
+
70
+ **Community Impact**: Demonstrating a pattern of violation of community standards, including sustained inappropriate behavior, harassment of an individual, or aggression toward or disparagement of classes of individuals.
71
+
72
+ **Consequence**: A permanent ban from any sort of public interaction within the community.
73
+
74
+ ## Attribution
75
+
76
+ This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 2.0,
77
+ available at https://www.contributor-covenant.org/version/2/0/code_of_conduct.html.
78
+
79
+ Community Impact Guidelines were inspired by [Mozilla's code of conduct enforcement ladder](https://github.com/mozilla/diversity).
80
+
81
+ [homepage]: https://www.contributor-covenant.org
82
+
83
+ For answers to common questions about this code of conduct, see the FAQ at
84
+ https://www.contributor-covenant.org/faq. Translations are available at https://www.contributor-covenant.org/translations.
data/Gemfile ADDED
@@ -0,0 +1,8 @@
1
+ # frozen_string_literal: true
2
+
3
+ source "https://rubygems.org"
4
+
5
+ # Specify your gem's dependencies in hbl_text.gemspec
6
+ gemspec
7
+
8
+ gem "rake", "~> 13.0"
data/README.md ADDED
@@ -0,0 +1,39 @@
1
+ # HblText
2
+
3
+ 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/hbl_text`. To experiment with that code, run `bin/console` for an interactive prompt.
4
+
5
+ TODO: Delete this and the text above, and describe your gem
6
+
7
+ ## Installation
8
+
9
+ Add this line to your application's Gemfile:
10
+
11
+ ```ruby
12
+ gem 'hbl_text'
13
+ ```
14
+
15
+ And then execute:
16
+
17
+ $ bundle install
18
+
19
+ Or install it yourself as:
20
+
21
+ $ gem install hbl_text
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. 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]/hbl_text. 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]/hbl_text/blob/master/CODE_OF_CONDUCT.md).
36
+
37
+ ## Code of Conduct
38
+
39
+ Everyone interacting in the HblText project's codebases, issue trackers, chat rooms and mailing lists is expected to follow the [code of conduct](https://github.com/[USERNAME]/hbl_text/blob/master/CODE_OF_CONDUCT.md).
data/Rakefile ADDED
@@ -0,0 +1,4 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "bundler/gem_tasks"
4
+ task default: %i[]
data/bin/console ADDED
@@ -0,0 +1,15 @@
1
+ #!/usr/bin/env ruby
2
+ # frozen_string_literal: true
3
+
4
+ require "bundler/setup"
5
+ require "hbl_text"
6
+
7
+ # You can add fixtures and/or initialization code here to make experimenting
8
+ # with your gem easier. You can also use a different console, if you like.
9
+
10
+ # (If you use this, don't forget to add pry to your Gemfile!)
11
+ # require "pry"
12
+ # Pry.start
13
+
14
+ require "irb"
15
+ IRB.start(__FILE__)
data/bin/setup ADDED
@@ -0,0 +1,8 @@
1
+ #!/usr/bin/env bash
2
+ set -euo pipefail
3
+ IFS=$'\n\t'
4
+ set -vx
5
+
6
+ bundle install
7
+
8
+ # Do any other automated setup that you need to do here
Binary file
Binary file
Binary file
Binary file
Binary file
Binary file
Binary file
Binary file
Binary file
Binary file
Binary file
data/hbl_text.gemspec ADDED
@@ -0,0 +1,45 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative "lib/hbl_text/version"
4
+
5
+ Gem::Specification.new do |spec|
6
+
7
+ spec.name = "hbl_text"
8
+ spec.version = HBLText::VERSION
9
+ spec.authors = ["Stephan Wenzel"]
10
+ spec.email = ["stephan.wenzel@drwpatent.de"]
11
+ spec.license = 'GPL-2.0-only'
12
+
13
+ spec.summary = "String utilities"
14
+ spec.description = "String utilities: handle encodings, create abbreviations"
15
+ spec.homepage = "https://github.com/HugoHasenbein/hbl_text"
16
+ spec.required_ruby_version = Gem::Requirement.new(">= 2.3.0")
17
+
18
+ spec.metadata["allowed_push_host"] = "https://rubygems.org"
19
+
20
+ spec.metadata["homepage_uri"] = spec.homepage
21
+ spec.metadata["source_code_uri"] = "https://github.com/HugoHasenbein/hbl_text"
22
+ spec.metadata["changelog_uri"] = "https://github.com/HugoHasenbein/hbl_text/Changelog.md"
23
+
24
+ # Specify which files should be added to the gem when it is released.
25
+ # The `git ls-files -z` loads the files in the RubyGem that have been added into git.
26
+ spec.files = Dir.chdir(File.expand_path('..', __FILE__)) do
27
+ `git ls-files -z`.split("\x0").reject { |f| f.match(%r{^(test|spec|features)/}) }
28
+ end
29
+
30
+ spec.bindir = "exe"
31
+ spec.executables = spec.files.grep(%r{\Aexe/}) { |f| File.basename(f) }
32
+ spec.require_paths = ["lib"]
33
+
34
+ # Specify which files should be added to the gem when it is released.
35
+ # The `git ls-files -z` loads the files in the RubyGem that have been added into git.
36
+ spec.files = Dir.chdir(File.expand_path('..', __FILE__)) do
37
+ `git ls-files -z`.split("\x0").reject { |f| f.match(%r{^(test|spec|features)/}) }
38
+ end
39
+
40
+ spec.bindir = "exe"
41
+ spec.executables = spec.files.grep(%r{^exe/}) { |f| File.basename(f) }
42
+ spec.require_paths = ["lib"]
43
+
44
+ # spec.add_runtime_dependency 'xxx'
45
+ end
@@ -0,0 +1,379 @@
1
+ # encoding: utf-8
2
+ #
3
+ # hbl_text provide text utilities
4
+ #
5
+ # Copyright © 2021 Stephan Wenzel <stephan.wenzel@drwpatent.de>
6
+ #
7
+ # This program is free software; you can redistribute it and/or
8
+ # modify it under the terms of the GNU General Public License
9
+ # as published by the Free Software Foundation; either version 2
10
+ # of the License, or (at your option) any later version.
11
+ #
12
+ # This program is distributed in the hope that it will be useful,
13
+ # but WITHOUT ANY WARRANTY; without even the implied warranty of
14
+ # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15
+ # GNU General Public License for more details.
16
+ #
17
+ # You should have received a copy of the GNU General Public License
18
+ # along with this program; if not, write to the Free Software
19
+ # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
20
+ #
21
+
22
+ module HBLText
23
+ module IDMaker
24
+ class << self
25
+ ##################################################################################
26
+ #
27
+ # constants
28
+ #
29
+ ##################################################################################
30
+ DEBUG = false
31
+ DEBUG2 = false
32
+
33
+ #
34
+ # find a pretty unique n-letter identifier for an arbitrary string
35
+ #
36
+ # string: (str) arbitrary string to create an identifier from
37
+ # n: (int) identifier length
38
+ # options:
39
+ # refs: (arr) list of existing (occupied) identifiers
40
+ # suffix: (str) suffix to add to create more choices for identifier creation
41
+ # f.i. "123456789"
42
+ # verbose: (bool) flag should output just identifier or id with meta info
43
+ # meta info: [id, method no., uggliness]
44
+ #
45
+ # remarks:
46
+ #
47
+ # identifier with only letters:
48
+ # 3 letters: 26^3 = 17.576 possible unique combinations
49
+ # 4 letters: 26^4 = 456.976 possible unique combinations
50
+ #
51
+ # letters and numbers:
52
+ # 3 digits: 36^3 = 46.656 possible unique combinations
53
+ # 4 digits: 36^4 = 1.679.616 possible unique combinations
54
+ #
55
+ #
56
+ def make_identifier( identifiable, n, **options)
57
+
58
+ refs = options[:refs] || []
59
+ suffix = options[:suffix] || ""
60
+ verbose = options[:verbose]
61
+
62
+ (0..(suffix.length + 1)).each do |pos|
63
+ ref, uggliness, method = find_identifier( identifiable, n, refs, suffix[0..pos])
64
+ Rails.logger.info [ref, method, sprintf("%04d", uggliness.presence || 9999), identifiable].map(&:to_s).join(" : ") if DEBUG || DEBUG2
65
+ if ref.present?
66
+ return verbose ? [ref, method, uggliness] : ref
67
+ end
68
+ end
69
+
70
+ return verbose ? [nil, nil, nil] : nil
71
+ end #def
72
+
73
+
74
+
75
+ ##################################################################################
76
+ #
77
+ # private
78
+ #
79
+ ##################################################################################
80
+ private
81
+
82
+ def find_identifier( identifiable, n, exclusions, suffix="")
83
+
84
+ method_counter = 0
85
+ #
86
+ # tidy up string, break into words, clean up words
87
+ #
88
+ words = identifiable.to_s
89
+ # first split name at boundaries between small and Capital,
90
+ # like "HelloWorld" => "Hello", "World", but leave lonely Capitals alone, like "GmbH"
91
+ words = words.split(/(?<=[a-z])(?=[A-Z][a-z])/)
92
+ # second split name at boundaries before Capital followed by small,
93
+ # like "ABCWorld" => "ABC", "World"
94
+ words = words.map{|word| word.split(/(?<=[A-Z])(?=[A-Z][a-z])/)}.flatten
95
+ # third split name at boundaries between literal and number,
96
+ # like "Ab17" => "Ab", "17"
97
+ words = words.map{|word| word.split(/(?<=[A-Za-z])(?=[0-9])/)}.flatten
98
+ # fourth split words at non literal/number boundaries,
99
+ # like "A, b" => "A", "b"
100
+ words = words.map{|word| word.split(/[^[[:alpha:]]^0-9]/)}.flatten
101
+ # filter empty strings
102
+ words = words.select(&:present?)
103
+ # upcase strings
104
+ words.map!(&:upcase) # tidy up
105
+
106
+ ################################################################################
107
+ #
108
+ # first letters of each word if enough words are present
109
+ #
110
+ # very intuitive abbreviation, very few available
111
+ #
112
+ # example:
113
+ # "JDL": "Jon Doe Ltd" for n= 3
114
+ #
115
+ # fails if n > number of words
116
+ #
117
+ ################################################################################
118
+ method_counter += 1
119
+ abbr, uggliness = abbreviation( words, n, n, exclusions, 1 )
120
+ return [abbr, uggliness, method_counter] if abbr.present?
121
+
122
+ ################################################################################
123
+ #
124
+ # first n letters of any word
125
+ #
126
+ # very intuitive abbreviation, very few available
127
+ #
128
+ # example:
129
+ # "JON", "DOE": "Jon Doe" for n= 3
130
+ #
131
+ # fails if n > length of any of the words
132
+ #
133
+ ################################################################################
134
+ method_counter += 1
135
+ abbr, uggliness = abbreviation( words, n, 1, exclusions, n )
136
+ return [abbr, uggliness, method_counter] if abbr.present?
137
+
138
+ ################################################################################
139
+ #
140
+ # first n-1 letter of any word plus one letter from next word (twosome combination)
141
+ #
142
+ # pretty good intuitive abbreviation, very few available
143
+ #
144
+ # example:
145
+ # "JOD", "Jon Doe" for n= 3
146
+ #
147
+ # fails if 2 > length of words
148
+ #
149
+ ################################################################################
150
+ method_counter += 1
151
+ if n > 1
152
+ abbr, uggliness = abbreviation( words, n, 2, exclusions, n-1 )
153
+ return [abbr, uggliness, method_counter] if abbr.present?
154
+ end
155
+
156
+ ################################################################################
157
+ #
158
+ # any submatch of letters
159
+ #
160
+ # less intuitive to poor intuitive abbreviation, very few available
161
+ #
162
+ # example:
163
+ # "OND", "Jon Doe" for n= 3
164
+ #
165
+ ################################################################################
166
+ method_counter += 1
167
+ abbr, uggliness = abbreviation( words.join("").split(//), n, n, exclusions, 1 )
168
+ return [abbr, uggliness, method_counter] if abbr.present?
169
+
170
+ ################################################################################
171
+ #
172
+ # any submatch of letters aided by suffix
173
+ #
174
+ # very poor intuitive abbreviation, very few available
175
+ #
176
+ # example:
177
+ # "ON5", "Jon Doe" for n= 3
178
+ #
179
+ ################################################################################
180
+ method_counter += 1
181
+ abbr, uggliness = abbreviation( (words << suffix).join("").split(//), n, n, exclusions, 1 )
182
+ return [abbr, uggliness, method_counter] if abbr.present?
183
+
184
+ return [nil, nil, nil] # uncomment to the following algorithms obsolete
185
+
186
+ #
187
+ #
188
+ #
189
+
190
+ ################################################################################
191
+ #
192
+ # n out of first n+1 beginning with first letter
193
+ #
194
+ # intuitive abbreviation, few available
195
+ #
196
+ # example:
197
+ # "JOA" or "DOD" for "Jonathan Doodle" for n = 3
198
+ #
199
+ # fails if length of not enough letters in string
200
+ #
201
+ ################################################################################
202
+ words.map{|w| w[0..n]}.each do |chunk|
203
+ if chunk.length > n
204
+ chars = chunk.split(//)
205
+ combs = chars.combination(n)
206
+ combs.each_with_index do |comb, i|
207
+ ref = comb.join("")
208
+ break if ref[0] != chunk[0] # do not accept refs not having same start letter
209
+ Rails.logger.info [ref, 2, 0].join("-") if DEBUG2
210
+ unless refs.include?(ref)
211
+ return [ref, 2, i]
212
+ end
213
+ end
214
+ else
215
+ Rails.logger.info [chunk, 2, 0].join("-") + " not feasible" if DEBUG2
216
+ end
217
+ end
218
+
219
+ ################################################################################
220
+ #
221
+ # n out on (first n) + (first from next word) beginning with first letter
222
+ #
223
+ # intuitive abbreviation, few available
224
+ #
225
+ # example:
226
+ # "JOD" for "Jonathan Doodle" for n = 3
227
+ #
228
+ # fails if only one word
229
+ #
230
+ ################################################################################
231
+ if words.length > 1
232
+ chunk = words[0][0..n-1].to_s + words[1][0].to_s
233
+ chars = chunk.split(//)
234
+ combs = chars.combination(n)
235
+ combs.each_with_index do |comb, i|
236
+ ref = comb.join("")
237
+ break if ref[0] != chunk[0] # do not accept refs not having same start letter
238
+ Rails.logger.info [ref, 3, 0].join("-") if DEBUG2
239
+ unless refs.include?(ref)
240
+ return [ref, 3, i]
241
+ end
242
+ end
243
+ else
244
+ Rails.logger.info [words.join(", "), 3, 0].join("-") + " not feasible" if DEBUG2
245
+ end
246
+
247
+ ################################################################################
248
+ #
249
+ # first n of any second word or later beginning with first letter of word
250
+ #
251
+ # intuitive abbreviation, few available
252
+ #
253
+ # example:
254
+ # "DOO" for "Jonathan Doodle" for n = 3
255
+ #
256
+ # fails if only one word
257
+ #
258
+ ################################################################################
259
+ if words.length > 1
260
+ chunks = words.map{|w| w[0..n-1]}.drop(1)
261
+ chunks.each_with_index do |ref, i|
262
+ if ref.length == n
263
+ Rails.logger.info [ref, 4, 0].join("-") if DEBUG2
264
+ unless refs.include?(ref)
265
+ return [ref, 4, i]
266
+ end
267
+ end
268
+ end
269
+ else
270
+ Rails.logger.info [words.join(", "), 4, 0].join("-") + " not feasible" if DEBUG2
271
+ end
272
+
273
+ ################################################################################
274
+ #
275
+ # first n of any second word or later beginning with first letter of word
276
+ #
277
+ # less intuitive abbreviation, most available
278
+ #
279
+ # example:
280
+ # "DE1" for "Jonathan Doe" for n = 3
281
+ #
282
+ # fails if no suffix present
283
+ #
284
+ ################################################################################
285
+ if suffix.present?
286
+ chunk = words.map{|w| w[0..n-1] + suffix }.drop(1)
287
+ chars = chunk.split(//)
288
+ combs = chars.combination(n)
289
+ combs.each_with_index do |comb, i|
290
+ ref = comb.join("")
291
+ break if ref[0] != chunk[0] # do not accept refs not having same start letter
292
+ Rails.logger.info [ref, 5, 0].join("-") if DEBUG2
293
+ unless refs.include?(ref)
294
+ return [ref, 5, i]
295
+ end
296
+ end
297
+ else
298
+ Rails.logger.info ["no suffix", 5, 0].join("-") + " not feasible" if DEBUG2
299
+ end
300
+
301
+ ################################################################################
302
+ #
303
+ # first n of any letter and suffix beginning with first letter of word
304
+ #
305
+ # much less intuitive abbreviation, many available
306
+ #
307
+ # example:
308
+ # "JN2" for "Jonathan Doe" for n = 3
309
+ #
310
+ #
311
+ ################################################################################
312
+ if suffix.present?
313
+ chunk = words.join("") + suffix
314
+ chars = chunk.split(//)
315
+ combs = chars.combination(n)
316
+ combs.each_with_index do |comb, i|
317
+ ref = comb.join("")
318
+ break if ref[0] != chunk[0] # do not accept refs not having same start letter
319
+ Rails.logger.info [ref, 6, 0].join("-") if DEBUG2
320
+ unless refs.include?(ref)
321
+ return [ref, 6, i]
322
+ end
323
+ end
324
+ else
325
+ Rails.logger.info ["no suffix", 6, 0].join("-") + " not feasible" if DEBUG2
326
+ end
327
+
328
+ ################################################################################
329
+ #
330
+ # any n of any letter and suffix
331
+ #
332
+ # pretty unintuitive abbreviation, very many available
333
+ #
334
+ # example:
335
+ # "ON2" for "Jonathan Doe" for n = 3
336
+ #
337
+ #
338
+ ################################################################################
339
+ if suffix.present?
340
+ chunk = words.join("") + suffix
341
+ chars = chunk.split(//)
342
+ combs = chars.combination(n)
343
+ combs.each_with_index do |comb, i|
344
+ ref = comb.join("")
345
+ Rails.logger.info [ref, 7, 0].join("-") if DEBUG2
346
+ unless refs.include?(ref)
347
+ return [ref, 7, i]
348
+ end
349
+ end
350
+ else
351
+ Rails.logger.info ["no suffix", 7, 0].join("-") + " not feasible" if DEBUG2
352
+ end
353
+
354
+ return [nil, nil, nil]
355
+
356
+ end #def
357
+
358
+ ##################################################################################
359
+ #
360
+ # abbreviation for an array of words
361
+ #
362
+ # words: array
363
+ # len: length of abbreviation
364
+ # items: number of words in abbreviation, i.e. 3 for "otf" for "one two five"
365
+ # exclusions: list of abbreviations in use
366
+ # stem: number of characters to take from each word
367
+ #
368
+ ##################################################################################
369
+ def abbreviation( words, len, items, exclusions, stem=1 )
370
+ words.combination(items).each_with_index do |combination, i|
371
+ abbr = combination.map{|word| word.first(stem) }.select{|w| w.length >= stem}.join("").first(len)
372
+ return [abbr, i] if abbr.present? && abbr.length == len && !exclusions.include?(abbr)
373
+ end
374
+ [nil, nil]
375
+ end #def
376
+
377
+ end #class
378
+ end #module
379
+ end #module
@@ -0,0 +1,146 @@
1
+ # encoding: utf-8
2
+ #
3
+ # hbl_text provide text utilities
4
+ #
5
+ # Copyright © 2021 Stephan Wenzel <stephan.wenzel@drwpatent.de>
6
+ #
7
+ # This program is free software; you can redistribute it and/or
8
+ # modify it under the terms of the GNU General Public License
9
+ # as published by the Free Software Foundation; either version 2
10
+ # of the License, or (at your option) any later version.
11
+ #
12
+ # This program is distributed in the hope that it will be useful,
13
+ # but WITHOUT ANY WARRANTY; without even the implied warranty of
14
+ # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15
+ # GNU General Public License for more details.
16
+ #
17
+ # You should have received a copy of the GNU General Public License
18
+ # along with this program; if not, write to the Free Software
19
+ # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
20
+ #
21
+
22
+ module HBLText
23
+ module Setter
24
+ class << self
25
+ ##################################################################################
26
+ #
27
+ # text encodings converter
28
+ #
29
+ ###################################################################################
30
+
31
+ #---------------------------------------------------------------------------------
32
+ # to_utf8
33
+ #---------------------------------------------------------------------------------
34
+ def to_utf8(arg, from_charset=nil)
35
+ case arg
36
+ when String
37
+ convert_encoding(arg, from_charset)
38
+ when Array
39
+ arg.map do |val|
40
+ to_utf8(val, from_charset)
41
+ end
42
+ when Hash
43
+ arg.map do |key, val|
44
+ [key, to_utf8(val, from_charset)]
45
+ end.to_h
46
+ else
47
+ arg
48
+ end
49
+ end #def
50
+
51
+ #---------------------------------------------------------------------------------
52
+ # convert_encoding
53
+ #---------------------------------------------------------------------------------
54
+ def convert_encoding( str, from_charset=nil )
55
+
56
+ encoding = from_charset || get_charset( str )
57
+
58
+ if encoding.present?
59
+ return str.encode( 'UTF-8', encoding,
60
+ :invalid => :replace,
61
+ :undef => :replace,
62
+ :replace => "?"
63
+ )
64
+ else
65
+ return str.encode( 'UTF-8',
66
+ :invalid => :replace,
67
+ :undef => :replace,
68
+ :replace => "?"
69
+ )
70
+ end #if
71
+ end #def
72
+
73
+ #---------------------------------------------------------------------------------
74
+ # get_charset
75
+ #---------------------------------------------------------------------------------
76
+ def get_charset( str )
77
+
78
+ ###########################################################
79
+ # work on local copy #
80
+ ###########################################################
81
+ str = str.dup
82
+
83
+ ###########################################################
84
+ # if string is valid return immediately #
85
+ ###########################################################
86
+ if str.force_encoding("UTF-8").valid_encoding?
87
+ return "UTF-8"
88
+ end
89
+
90
+ ###########################################################
91
+ # now, try the most often string encodings #
92
+ ###########################################################
93
+ encodings = %w(Windows-1252 Windows-1251 ISO-8859-1 Macintosh)
94
+ encodings.each do |enc|
95
+ return enc if str.force_encoding( enc ).valid_encoding?
96
+ end
97
+
98
+ ###########################################################
99
+ # if we are here, then some other encoding is used #
100
+ # Encoding list: run through all available encodings #
101
+ ###########################################################
102
+ Encoding.list.each do |enc|
103
+ return enc if str.force_encoding( enc ).valid_encoding?
104
+ end
105
+
106
+ ###########################################################
107
+ # this code is only reached if everything else failed #
108
+ ###########################################################
109
+ # here we give up and set to no encoding
110
+ return nil
111
+
112
+ end #def
113
+
114
+ #---------------------------------------------------------------------------------
115
+ # get_charset_from_tag
116
+ #---------------------------------------------------------------------------------
117
+ def get_charset_from_tag( str )
118
+
119
+ # create HTML from fragment
120
+ html = Nokogiri::HTML::fragment(to_utf8(str))
121
+
122
+ # create Nokokiris XPath expression to match 'meta', 'charset', 'content-type'
123
+ # and 'content' in a case insensitive way
124
+ values = []
125
+ downcased_name = "translate(local-name(), 'ABCDEFGHIJKLMNOPQRSTUVWXYZ', 'abcdefghijklmnopqrstuvwxyz')='meta'"
126
+ downcased_chrs = "translate(local-name(), 'ABCDEFGHIJKLMNOPQRSTUVWXYZ', 'abcdefghijklmnopqrstuvwxyz')='charset'"
127
+ downcased_attr = "translate(@http-equiv, 'ABCDEFGHIJKLMNOPQRSTUVWXYZ', 'abcdefghijklmnopqrstuvwxyz')='content-type'"
128
+ downcased_getr = "translate(local-name(), 'ABCDEFGHIJKLMNOPQRSTUVWXYZ', 'abcdefghijklmnopqrstuvwxyz')='content'"
129
+
130
+ # case insensitive fetch <meta charset="whatever">
131
+ values << html.xpath("./*[#{downcased_name}]/@*[#{downcased_chrs}]").last.try(:value)
132
+
133
+ # case insensitive fetch <meta http-equiv="Content-Type" content="anything; charset=whatever>"
134
+ value = html.xpath("./*[#{downcased_name}][#{downcased_attr}]/@*[#{downcased_getr}]").last.try(:value)
135
+ value = value.to_s.split(/;/).
136
+ select{|s| s =~ /\s*(?<=charset=).*/}.
137
+ map{|s| s.match(/\s*(?<=charset=)(.*)/)}.
138
+ compact.last.try(:[],1)
139
+
140
+ values << value
141
+ values.compact.last
142
+ end #def
143
+
144
+ end #class
145
+ end #module
146
+ end #module
@@ -0,0 +1,32 @@
1
+ # encoding: utf-8
2
+ #
3
+ # hbl_text provide text utilities
4
+ #
5
+ # Copyright © 2021 Stephan Wenzel <stephan.wenzel@drwpatent.de>
6
+ #
7
+ # This program is free software; you can redistribute it and/or
8
+ # modify it under the terms of the GNU General Public License
9
+ # as published by the Free Software Foundation; either version 2
10
+ # of the License, or (at your option) any later version.
11
+ #
12
+ # This program is distributed in the hope that it will be useful,
13
+ # but WITHOUT ANY WARRANTY; without even the implied warranty of
14
+ # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15
+ # GNU General Public License for more details.
16
+ #
17
+ # You should have received a copy of the GNU General Public License
18
+ # along with this program; if not, write to the Free Software
19
+ # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
20
+ #
21
+
22
+ class String
23
+
24
+ def to_utf8(from_charset=nil)
25
+ HBLText::Setter.convert_encoding(self, from_charset)
26
+ end #def
27
+
28
+ def to_utf8!(from_charset=nil)
29
+ replace(HBLText::Setter.convert_encoding(self, from_charset))
30
+ end #def
31
+
32
+ end #class
@@ -0,0 +1,5 @@
1
+ # frozen_string_literal: true
2
+
3
+ module HBLText
4
+ VERSION = "0.1.11"
5
+ end
data/lib/hbl_text.rb ADDED
@@ -0,0 +1,25 @@
1
+ # encoding: utf-8
2
+ #
3
+ # hbl_text provide text utilities
4
+ #
5
+ # Copyright © 2021 Stephan Wenzel <stephan.wenzel@drwpatent.de>
6
+ #
7
+ # This program is free software; you can redistribute it and/or
8
+ # modify it under the terms of the GNU General Public License
9
+ # as published by the Free Software Foundation; either version 2
10
+ # of the License, or (at your option) any later version.
11
+ #
12
+ # This program is distributed in the hope that it will be useful,
13
+ # but WITHOUT ANY WARRANTY; without even the implied warranty of
14
+ # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15
+ # GNU General Public License for more details.
16
+ #
17
+ # You should have received a copy of the GNU General Public License
18
+ # along with this program; if not, write to the Free Software
19
+ # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
20
+ #
21
+
22
+ require "hbl_text/version"
23
+ require "hbl_text/id_maker"
24
+ require "hbl_text/setter"
25
+ require "hbl_text/string"
metadata ADDED
@@ -0,0 +1,72 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: hbl_text
3
+ version: !ruby/object:Gem::Version
4
+ version: 0.1.11
5
+ platform: ruby
6
+ authors:
7
+ - Stephan Wenzel
8
+ autorequire:
9
+ bindir: exe
10
+ cert_chain: []
11
+ date: 2021-10-11 00:00:00.000000000 Z
12
+ dependencies: []
13
+ description: 'String utilities: handle encodings, create abbreviations'
14
+ email:
15
+ - stephan.wenzel@drwpatent.de
16
+ executables: []
17
+ extensions: []
18
+ extra_rdoc_files: []
19
+ files:
20
+ - ".gitignore"
21
+ - CODE_OF_CONDUCT.md
22
+ - Gemfile
23
+ - README.md
24
+ - Rakefile
25
+ - bin/console
26
+ - bin/setup
27
+ - hbl_text-0.1.0.gem
28
+ - hbl_text-0.1.1.gem
29
+ - hbl_text-0.1.10.gem
30
+ - hbl_text-0.1.2.gem
31
+ - hbl_text-0.1.3.gem
32
+ - hbl_text-0.1.4.gem
33
+ - hbl_text-0.1.5.gem
34
+ - hbl_text-0.1.6.gem
35
+ - hbl_text-0.1.7.gem
36
+ - hbl_text-0.1.8.gem
37
+ - hbl_text-0.1.9.gem
38
+ - hbl_text.gemspec
39
+ - lib/hbl_text.rb
40
+ - lib/hbl_text/id_maker.rb
41
+ - lib/hbl_text/setter.rb
42
+ - lib/hbl_text/string.rb
43
+ - lib/hbl_text/version.rb
44
+ homepage: https://github.com/HugoHasenbein/hbl_text
45
+ licenses:
46
+ - GPL-2.0-only
47
+ metadata:
48
+ allowed_push_host: https://rubygems.org
49
+ homepage_uri: https://github.com/HugoHasenbein/hbl_text
50
+ source_code_uri: https://github.com/HugoHasenbein/hbl_text
51
+ changelog_uri: https://github.com/HugoHasenbein/hbl_text/Changelog.md
52
+ post_install_message:
53
+ rdoc_options: []
54
+ require_paths:
55
+ - lib
56
+ required_ruby_version: !ruby/object:Gem::Requirement
57
+ requirements:
58
+ - - ">="
59
+ - !ruby/object:Gem::Version
60
+ version: 2.3.0
61
+ required_rubygems_version: !ruby/object:Gem::Requirement
62
+ requirements:
63
+ - - ">="
64
+ - !ruby/object:Gem::Version
65
+ version: '0'
66
+ requirements: []
67
+ rubyforge_project:
68
+ rubygems_version: 2.6.14
69
+ signing_key:
70
+ specification_version: 4
71
+ summary: String utilities
72
+ test_files: []