Class: String
- Inherits:
-
Object
- Object
- String
- 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
-
#constantize ⇒ String
Tries to find a constant with the name specified by this
String
:. -
#dash_case ⇒ String
Converts a string to dash case.
-
#snake_case ⇒ String
Converts a string to snake case.
-
#space_case ⇒ String
Converts a string to space case.
-
#to_b ⇒ Boolean
Converts a
String
to a boolean.
Instance Method Details
#constantize ⇒ String
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
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_case ⇒ String
Converts a string to dash case. For example, the String Foo::DashCase
would become dash-case
.
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_case ⇒ String
Converts a string to snake case. For example, the String Rattle::SnakeCase
would become rattle/snake_case
.
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_case ⇒ String
Converts a string to space case. For example, the String SpaceCase
would become Space Case.
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_b ⇒ Boolean
Converts a String
to a boolean
22 23 24 |
# File 'lib/buildpack_support/to_b.rb', line 22 def to_b downcase == 'true' end |