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
-
#camel_case(str) ⇒ String
Camel case the string, like Rails’ String#classify method.
-
#clean_up_punctuation(str) ⇒ String
Strip all characters that can’t go into a constant name.
-
#snake_case(str) ⇒ String
Snake case the string, like Rails’ String#underscore method.
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.
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.
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’.
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 |