Class: String

Inherits:
Object
  • Object
show all
Defined in:
lib/buildpack_support/to_b.rb,
lib/buildpack_support/dash_case.rb,
lib/buildpack_support/snake_case.rb,
lib/buildpack_support/space_case.rb,
lib/buildpack_support/constantize.rb

Overview

A mixin that adds the ability to turn a String into a constant.

Instance Method Summary collapse

Instance Method Details

#constantizeString

Tries to find a constant with the name specified by this String:

"Module".constantize     # => Module
"Test::Unit".constantize # => Test::Unit

The name is assumed to be the one of a top-level constant, no matter whether it starts with “::” or not. No lexical context is taken into account:

C = 'outside'
module M
  C = 'inside'
  C               # => 'inside'
  "C".constantize # => 'outside', same as ::C
end

Returns:

  • (String)

    The constantized rendering of this String.

Raises:

  • NameError if the name is not in CamelCase or the constant is unknown.



36
37
38
39
40
41
42
43
44
45
# File 'lib/buildpack_support/constantize.rb', line 36

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

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

#dash_caseString

Converts a string to dash case. For example, the String Foo::DashCase would become dash-case.

Returns:

  • (String)

    The dash case rendering of this String



22
23
24
25
26
27
# File 'lib/buildpack_support/dash_case.rb', line 22

def dash_case
  split('::').last
  .gsub(/([A-Z]+)([A-Z][a-z])/, '\1-\2')
  .gsub(/([a-z\d])([A-Z])/, '\1-\2')
  .downcase
end

#snake_caseString

Converts a string to snake case. For example, the String Rattle::SnakeCase would become rattle/snake_case.

Returns:

  • (String)

    The snake case rendering of this String



22
23
24
25
26
27
28
# File 'lib/buildpack_support/snake_case.rb', line 22

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

#space_caseString

Converts a string to space case. For example, the String SpaceCase would become Space Case.

Returns:

  • (String)

    The space case rendering of this String



22
23
24
25
26
27
# File 'lib/buildpack_support/space_case.rb', line 22

def space_case
  split('::').last
  .gsub(/([A-Z]+)([A-Z][a-z])/, '\1 \2')
  .gsub(/([a-z\d])([A-Z])/, '\1 \2')
  .tr('-', ' ')
end

#to_bBoolean

Converts a String to a boolean

Returns:

  • (Boolean)

    true if <STRING>.downcase == ‘true’. false otherwise



22
23
24
# File 'lib/buildpack_support/to_b.rb', line 22

def to_b
  downcase == 'true'
end