Class: String

Inherits:
Object
  • Object
show all
Defined in:
lib/core_ext/string_extension.rb

Overview

Extend string with helpers specificic to this gem.

Constant Summary collapse

MM_Acronyms =
%w(AD DCHP DHCP DNS ID IP IPAM PTR VLAN VRF).freeze
MM_Upper_In_Camel =
%w(VLAN VRF).freeze

Instance Method Summary collapse

Instance Method Details

#mm_camelizeObject

Convert snake case to camel case while honoring acronyms.



31
32
33
34
35
36
37
38
# File 'lib/core_ext/string_extension.rb', line 31

def mm_camelize
  first = split('_')[0]
  first = first.upcase if MM_Upper_In_Camel.include?(first.upcase)
  remaining = split('_').drop(1)
  camelized = remaining.map { |p| mm_capitalize_with_acronyms(p) }
  camelized.insert(0, first)
  camelized.join
end

#mm_pascalizeObject

Convert snake case to Pascal case while honoring acronyms.



41
42
43
# File 'lib/core_ext/string_extension.rb', line 41

def mm_pascalize
  split('_').map { |p| mm_capitalize_with_acronyms(p) }.join
end

#mm_pluralizeObject

Simplistic pluralization for M&M types



46
47
48
49
50
51
52
# File 'lib/core_ext/string_extension.rb', line 46

def mm_pluralize
  if self =~ /y$/
    "#{chomp('y')}ies"
  else
    "#{self}s"
  end
end

#mm_underscoreObject

Underscore functionality to match conversion from M&M values.



7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
# File 'lib/core_ext/string_extension.rb', line 7

def mm_underscore
  return self if self =~ /^[a-z_]+$/

  # handle fields that are IDs
  underscored = gsub(/IDs/, '_ids')

  # break on lower to upper transition
  underscored.gsub!(/([a-z])([A-Z]+)/) do
    "#{Regexp.last_match(1)}_#{Regexp.last_match(2)}"
  end

  # break on acronym to caps word transition
  underscored.gsub!(/([A-Z])([A-Z][a-z]+)/) do
    "#{Regexp.last_match(1)}_#{Regexp.last_match(2)}"
  end

  # special case separation
  underscored.gsub!(/DNSPTR/i, 'dns_ptr')
  underscored.gsub!(/VLANID/i, 'vlan_id')

  underscored.downcase
end