Module: FlossFunding::UnderBar
- Defined in:
- lib/floss_funding/under_bar.rb
Overview
Utilities to convert Ruby namespaces to safe, uppercased, underscore forms
for environment variable names. Protects against malicious or invalid class
names via conservative character rules.
See also: https://github.com/galtzo-floss/shields-badge/blob/main/lib/shields/badge.rb
Constant Summary collapse
- SAFE_TO_UNDERSCORE =
Allowed characters for a single namespace segment. Max length 256 to avoid abuse.
/\A[\p{UPPERCASE-LETTER}\p{LOWERCASE-LETTER}\p{DECIMAL-NUMBER}]{1,256}\Z/
- SUBBER_UNDER =
Pattern to insert underscores before capital letters.
/(\p{UPPERCASE-LETTER})/
- INITIAL_UNDERSCORE =
Pattern for a leading underscore to be removed after transformation.
/^_/
Class Method Summary collapse
-
._cache ⇒ Object
Internal memoization cache for env var names.
-
.env_variable_name(namespace) ⇒ String
Builds an uppercased ENV variable name from a Ruby namespace.
-
.reset_cache! ⇒ Object
-
.to_under_bar(string) ⇒ String
Converts a single namespace segment to an underscored, uppercased string.
Class Method Details
._cache ⇒ Object
Internal memoization cache for env var names
22 23 24 |
# File 'lib/floss_funding/under_bar.rb', line 22 def _cache @cache ||= {} end |
.env_variable_name(namespace) ⇒ String
Builds an uppercased ENV variable name from a Ruby namespace.
35 36 37 38 39 40 41 42 43 44 45 46 47 |
# File 'lib/floss_funding/under_bar.rb', line 35 def env_variable_name(namespace) return namespace.env_var_name if namespace.respond_to?(:env_var_name) raise FlossFunding::Error, "namespace must be a String, but is #{namespace.class}" unless namespace.is_a?(String) cached = _cache[namespace] return cached if cached name_parts = namespace.split("::") env_name = name_parts.map { |np| (np) }.join("__") result = "#{::FlossFunding::Constants::DEFAULT_PREFIX}#{env_name}".upcase _cache[namespace] = result.freeze end |
.reset_cache! ⇒ Object
26 27 28 |
# File 'lib/floss_funding/under_bar.rb', line 26 def reset_cache! @cache = {} end |
.to_under_bar(string) ⇒ String
Converts a single namespace segment to an underscored, uppercased string.
54 55 56 57 58 59 60 61 |
# File 'lib/floss_funding/under_bar.rb', line 54 def (string) safe = string[SAFE_TO_UNDERSCORE] raise FlossFunding::Error, "Invalid! Each part of klass name must match #{SAFE_TO_UNDERSCORE}: #{safe} (#{safe.class}) != #{string[0..255]} (#{string.class})" unless safe == string.to_s underscored = safe.gsub(SUBBER_UNDER) { "_#{$1}" } shifted_leading_underscore = underscored.sub(INITIAL_UNDERSCORE, "") shifted_leading_underscore.upcase end |