module Nuggets::String::CamelscoreMixin

Constants

CAMELSCORE_ACRONYMS

List of acronyms to treat specially in camelcase and underscore.

Public Instance Methods

camelcase → new_string click to toggle source

Returns the CamelCase form of str.

# File lib/nuggets/string/camelscore_mixin.rb, line 45
def camelcase
  dup.camelcase!
end
Also aliased as: camelize
camelcase! → str click to toggle source

Replaces str with its CamelCase form and returns str.

# File lib/nuggets/string/camelscore_mixin.rb, line 55
def camelcase!
  sub!(/^[a-z]+/) {
    CAMELSCORE_ACRONYMS[$&] || $&.capitalize
  }

  gsub!(/(?:_|([\/\d]))([a-z]+)/i) {
    "#{$1}#{CAMELSCORE_ACRONYMS[$2] || $2.capitalize}"
  }

  gsub!('/', '::')

  self
end
Also aliased as: camelize!
camelize()
Alias for: camelcase
camelize!()
Alias for: camelcase!
constantize(base = Object) → anObject click to toggle source

Returns the constant pointed to by str, relative to base.

# File lib/nuggets/string/camelscore_mixin.rb, line 105
def constantize(base = ::Object)
  names = split('::')
  return if names.empty?

  const = names.first.empty? ? (names.shift; ::Object) : base
  names.each { |name| const = const.const_get(name) }
  const
end
underscore → new_string click to toggle source

Returns the under_score form of str.

# File lib/nuggets/string/camelscore_mixin.rb, line 75
def underscore
  dup.underscore!
end
underscore! → str click to toggle source

Replaces str with its under_score form and returns str.

# File lib/nuggets/string/camelscore_mixin.rb, line 83
def underscore!
  gsub!(/::/, '/')

  a = CAMELSCORE_ACRONYMS.values
  r = a.empty? ? /(?=a)b/ : ::Regexp.union(*a.sort_by { |v| v.length })

  gsub!(/(?:([A-Za-z])|(\d)|^)(#{r})(?=\b|[^a-z])/) {
    "#{$1 || $2}#{'_' if $1}#{$3.downcase}"
  }

  gsub!(/([A-Z])(?=[A-Z])/, '\1_')
  gsub!(/([a-z\d])([A-Z])/, '\1_\2')

  downcase!

  self
end