Module: Emittance::Helpers::StringHelpers

Included in:
EventLookup, EventLookup::EventKlassConverter
Defined in:
lib/emittance/helpers/string_helpers.rb

Overview

Some helper methods to mix in for the purposes of manipulating strings.

Instance Method Summary collapse

Instance Method Details

#camel_case(str) ⇒ String

Camel case the string, like Rails’ String#classify method. This essentially works like the inverse of snake_case, so ‘foo/bar_baz’ becomes ‘Foo::BarBaz’. There is one one notable exception:

camel_case(snake_case('APIFoo'))
# => 'ApiFoo'

As such, be mindful when naming your classes.

Parameters:

  • str (String)

    the string you wish to convert

Returns:

  • (String)

    a new string converted to camel case.



33
34
35
36
37
# File 'lib/emittance/helpers/string_helpers.rb', line 33

def camel_case(str)
  str = str.sub(/^[a-z\d]*/) { $&.capitalize }
  str = str.gsub(%r{(?:_|(\/))([a-z\d]*)}) { "#{Regexp.last_match(1)}#{Regexp.last_match(2).capitalize}" }
  str.gsub(%r{\/}, '::')
end

#clean_up_punctuation(str) ⇒ String

Strip all characters that can’t go into a constant name.

Parameters:

  • str (String)

    the string from which you want to remove punctuation

Returns:

  • (String)

    a new string with punctuation stripped



43
44
45
# File 'lib/emittance/helpers/string_helpers.rb', line 43

def clean_up_punctuation(str)
  str.gsub(%r{[^A-Za-z\d\_\:\/]}, '')
end

#snake_case(str) ⇒ String

Snake case the string, like Rails’ String#underscore method. As such, strings that look like namespaced constants will have the namespace resolver operators replaced with / characters, rather than underscores. For example: ‘Foo::BarBaz’ becomes ‘foo/bar_baz’.

Parameters:

  • str (String)

    the string you wish to convert

Returns:

  • (String)

    a new string that is the snake-cased version of the old string



15
16
17
18
19
20
21
# File 'lib/emittance/helpers/string_helpers.rb', line 15

def snake_case(str)
  str.gsub(/::/, '/')
    .gsub(/([A-Z]+)([A-Z][a-z])/, '\1_\2')
    .gsub(/([a-z\d])([A-Z])/, '\1_\2')
    .tr('-', '_')
    .downcase
end