Class: EacRubyUtils::Inflector

Inherits:
Object
  • Object
show all
Defined in:
lib/eac_ruby_utils/inflector.rb

Constant Summary collapse

VARIABLE_NAME_PATTERN =
/[_a-z][_a-z0-9]*/i.freeze

Class Method Summary collapse

Class Method Details

.variableize(string, validate = true) ⇒ String?

Convert a string to a variable format: first character as a lowercase letter or underscore and other as a lowercase letter, underscore or numbers.

Parameters:

  • string (String)

    The source string.

  • validate (Boolean) (defaults to: true)

    Affect the outcome when the result builded is not in a valid variable format. If ‘true`, it raises a ArgumentError. If `false`, return `nil`.

Returns:

Raises:

  • (ArgumentError)


17
18
19
20
21
22
23
24
25
26
# File 'lib/eac_ruby_utils/inflector.rb', line 17

def variableize(string, validate = true) # rubocop:disable Style/OptionalBooleanParameter
  r = ::ActiveSupport::Inflector.transliterate(string).gsub(/[^_a-z0-9]/i, '_')
        .gsub(/_+/, '_').gsub(/_\z/, '').gsub(/\A_/, '').downcase
  m = VARIABLE_NAME_PATTERN.match(r)
  return r if m
  return nil unless validate

  raise ::ArgumentError, "Invalid variable name \"#{r}\" was generated " \
                         "from string \"#{string}\""
end