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.

Returns:

  • (Regexp)
/\A[\p{UPPERCASE-LETTER}\p{LOWERCASE-LETTER}\p{DECIMAL-NUMBER}]{1,256}\Z/
SUBBER_UNDER =

Pattern to insert underscores before capital letters.

Returns:

  • (Regexp)
/(\p{UPPERCASE-LETTER})/
INITIAL_UNDERSCORE =

Pattern for a leading underscore to be removed after transformation.

Returns:

  • (Regexp)
/^_/

Class Method Summary collapse

Class Method Details

.env_variable_name(opts = {}) ⇒ String

Builds an uppercased ENV variable name from a Ruby namespace.

Parameters:

  • opts (Hash) (defaults to: {})

Options Hash (opts):

  • :namespace (String) — default: required

    the Ruby namespace (e.g., “My::Lib”)

Returns:

  • (String)

    the resulting ENV variable name

Raises:



27
28
29
30
31
32
33
34
# File 'lib/floss_funding/under_bar.rb', line 27

def env_variable_name(opts = {})
  namespace = opts[:namespace]
  raise FlossFunding::Error, "namespace must be a String, but is #{namespace.class}" unless namespace.is_a?(String)

  name_parts = namespace.split("::")
  env_name = name_parts.map { |np| to_under_bar(np) }.join("_")
  "#{::FlossFunding::Constants::DEFAULT_PREFIX}#{env_name}".upcase
end

.to_under_bar(string) ⇒ String

Converts a single namespace segment to an underscored, uppercased string.

Parameters:

  • string (String)

    the namespace segment to convert

Returns:

  • (String)

    an uppercased, underscore-separated representation

Raises:



41
42
43
44
45
46
47
48
# File 'lib/floss_funding/under_bar.rb', line 41

def to_under_bar(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