Module: Apiture::Utils::Inflections

Extended by:
Inflections
Included in:
APIBuilder, RequestContext, Swagger::Node, Swagger::Parser, Inflections
Defined in:
lib/apiture/utils/inflections.rb

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.acronym_regexObject



9
10
11
# File 'lib/apiture/utils/inflections.rb', line 9

def self.acronym_regex
  @@acronym_regex ||= /(?=a)b/
end

.acronymsObject



5
6
7
# File 'lib/apiture/utils/inflections.rb', line 5

def self.acronyms
  @@acronyms ||= {}
end

Instance Method Details

#camelize(term, uppercase_first_letter = true) ⇒ Object



13
14
15
16
17
18
19
20
21
22
23
# File 'lib/apiture/utils/inflections.rb', line 13

def camelize(term, uppercase_first_letter = true)
  string = term.to_s
  if uppercase_first_letter
    string = string.sub(/^[a-z\d]*/) { ::Apiture::Utils::Inflections.acronyms[$&] || $&.capitalize }
  else
    string = string.sub(/^(?:#{::Apiture::Utils::Inflections.acronym_regex}(?=\b|[A-Z_])|\w)/) { $&.downcase }
  end
  string.gsub!(/(?:_|(\/))([a-z\d]*)/) { "#{$1}#{::Apiture::Utils::Inflections.acronyms[$2] || $2.capitalize}" }
  string.gsub!('/', '::')
  string
end

#constantize(camel_cased_word) ⇒ Object



35
36
37
38
39
40
41
# File 'lib/apiture/utils/inflections.rb', line 35

def constantize(camel_cased_word)
  unless /\A(?:::)?([A-Z]\w*(?:::[A-Z]\w*)*)\z/ =~ camel_cased_word
    raise NameError, "#{camel_cased_word.inspect} is not a valid constant name!"
  end

  Object.module_eval("::#{$1}", __FILE__, __LINE__)
end

#underscore(camel_cased_word) ⇒ Object



25
26
27
28
29
30
31
32
33
# File 'lib/apiture/utils/inflections.rb', line 25

def underscore(camel_cased_word)
  word = camel_cased_word.to_s.gsub('::', '/')
  word.gsub!(/(?:([A-Za-z\d])|^)(#{::Apiture::Utils::Inflections.acronym_regex})(?=\b|[^a-z])/) { "#{$1}#{$1 && '_'}#{$2.downcase}" }
  word.gsub!(/([A-Z\d]+)([A-Z][a-z])/,'\1_\2')
  word.gsub!(/([a-z\d])([A-Z])/,'\1_\2')
  word.tr!("-", "_")
  word.downcase!
  word
end