Module: Surrealist::StringUtils
- Defined in:
- lib/surrealist/string_utils.rb
Overview
A helper class for strings transformations.
Constant Summary collapse
- DASH =
'-'
- UNDERSCORE =
'_'
- EMPTY_STRING =
''
- DASH_REGEXP1 =
/([A-Z]+)([A-Z][a-z])/o.freeze
- DASH_REGEXP2 =
/([a-z\d])([A-Z])/o.freeze
- UNDERSCORE_REGEXP =
/(?:^|_)([^_\s]+)/o.freeze
- NAMESPACES_SEPARATOR =
'::'
- UNDERSCORE_SUBSTITUTE =
'\1_\2'
Class Method Summary collapse
-
.break_namespaces(klass, camelize, nesting_level) ⇒ Hash
Extracts n amount of classes from a namespaces and returns a nested hash.
-
.camelize(snake_string, first_upper: true) ⇒ String
Camelizes a string.
-
.extract_class(string) ⇒ String
Extracts bottom-level class from a namespace.
-
.underscore(string) ⇒ String
Converts a string to snake_case.
Class Method Details
.break_namespaces(klass, camelize, nesting_level) ⇒ Hash
Extracts n amount of classes from a namespaces and returns a nested hash.
72 73 74 75 76 77 78 79 80 |
# File 'lib/surrealist/string_utils.rb', line 72 def break_namespaces(klass, camelize, nesting_level) Surrealist::ExceptionRaiser.raise_invalid_nesting!(nesting_level) unless nesting_level.positive? klass.split(NAMESPACES_SEPARATOR).last(nesting_level).reverse!.inject({}) do |a, n| key = (camelize ? camelize(uncapitalize(n), first_upper: false) : underscore(n)).to_sym { key => a } end end |
.camelize(snake_string, first_upper: true) ⇒ String
Camelizes a string.
36 37 38 39 40 41 42 43 44 |
# File 'lib/surrealist/string_utils.rb', line 36 def camelize(snake_string, first_upper: true) if first_upper snake_string.to_s.gsub(UNDERSCORE_REGEXP) { Regexp.last_match[1].capitalize } else parts = snake_string.split(UNDERSCORE, 2) parts[0].concat(camelize(parts[1])) if parts.size > 1 parts[0] || EMPTY_STRING end end |
.extract_class(string) ⇒ String
Extracts bottom-level class from a namespace.
54 55 56 |
# File 'lib/surrealist/string_utils.rb', line 54 def extract_class(string) uncapitalize(string.split(NAMESPACES_SEPARATOR).last) end |
.underscore(string) ⇒ String
Converts a string to snake_case.
21 22 23 24 25 26 27 28 |
# File 'lib/surrealist/string_utils.rb', line 21 def underscore(string) dup = string.gsub(NAMESPACES_SEPARATOR, UNDERSCORE) dup.gsub!(DASH_REGEXP1, UNDERSCORE_SUBSTITUTE) dup.gsub!(DASH_REGEXP2, UNDERSCORE_SUBSTITUTE) dup.tr!(DASH, UNDERSCORE) dup.downcase! dup end |