Class: String

Inherits:
Object
  • Object
show all
Defined in:
lib/rainman/support.rb

Overview

From activesupport/lib/active_support/inflector/methods.rb

Instance Method Summary collapse

Instance Method Details

#camelize(first_letter_in_uppercase = true) ⇒ Object

Public: Camel-case a string.

Examples

"foo_bar"     #=> "FooBar"
"foo_bar/baz" #=> "FooBar::Baz"

Returns a String.



32
33
34
35
36
37
38
# File 'lib/rainman/support.rb', line 32

def camelize(first_letter_in_uppercase = true)
  if first_letter_in_uppercase
    gsub(/\/(.?)/) { "::#{$1.upcase}" }.gsub(/(?:^|_)(.)/) { $1.upcase }
  else
    self[0].chr.downcase + camelize(self)[1..-1]
  end
end

#constantizeObject

Public: Convert a string into a constant. The constant must exist in ObjectSpace.

Raises NameError if the constant does not exist.

Returns a constant.



13
14
15
16
17
18
19
20
21
22
# File 'lib/rainman/support.rb', line 13

def constantize
  names = split('::')
  names.shift if names.empty? || names.first.empty?

  constant = Object
  names.each do |name|
    constant = constant.const_defined?(name) ? constant.const_get(name) : constant.const_missing(name)
  end
  constant
end

#underscoreObject

Makes an underscored, lowercase form from the expression in the string.

Changes ‘::’ to ‘/’ to convert namespaces to paths.

Examples:

"ActiveModel".underscore         # => "active_model"
"ActiveModel::Errors".underscore # => "active_model/errors"

As a rule of thumb you can think of underscore as the inverse of camelize, though there are cases where that does not hold:

"SSLError".underscore.camelize # => "SslError"


52
53
54
55
56
57
58
# File 'lib/rainman/support.rb', line 52

def underscore
  gsub(/::/, '/').
    gsub(/([A-Z]+)([A-Z][a-z])/,'\1_\2').
    gsub(/([a-z\d])([A-Z])/,'\1_\2').
    tr("-", "_").
    downcase
end