Module: Nuggets::String::CamelscoreMixin

Included in:
String
Defined in:
lib/nuggets/string/camelscore_mixin.rb

Constant Summary collapse

CAMELSCORE_ACRONYMS =

List of acronyms to treat specially in #camelcase and #underscore.

{
  'html' => 'HTML',
  'rss'  => 'RSS',
  'sql'  => 'SQL',
  'ssl'  => 'SSL',
  'xml'  => 'XML'
}

Instance Method Summary collapse

Instance Method Details

#camelcaseObject Also known as: camelize

call-seq:

str.camelcase => new_string

Returns the CamelCase form of str.



45
46
47
# File 'lib/nuggets/string/camelscore_mixin.rb', line 45

def camelcase
  dup.camelcase!
end

#camelcase!Object Also known as: camelize!

call-seq:

str.camelcase! => str

Replaces str with its CamelCase form and returns str.



55
56
57
58
59
60
61
62
63
64
65
66
67
# 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

#constantize(base = ::Object) ⇒ Object

call-seq:

str.constantize(base = Object) => anObject

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



105
106
107
108
109
110
111
112
# 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

#underscoreObject

call-seq:

str.underscore => new_string

Returns the under_score form of str.



75
76
77
# File 'lib/nuggets/string/camelscore_mixin.rb', line 75

def underscore
  dup.underscore!
end

#underscore!Object

call-seq:

str.underscore! => str

Replaces str with its under_score form and returns str.



83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
# 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