Class: String

Inherits:
Object show all
Defined in:
lib/nanite/util.rb

Instance Method Summary collapse

Instance Method Details

#snake_caseString

Convert to snake case.

"FooBar".snake_case           #=> "foo_bar"
"HeadlineCNNNews".snake_case  #=> "headline_cnn_news"
"CNN".snake_case              #=> "cnn"

Returns:

  • (String)

    Receiver converted to snake case.



12
13
14
15
16
# File 'lib/nanite/util.rb', line 12

def snake_case
  return self.downcase if self =~ /^[A-Z]+$/
  self.gsub(/([A-Z]+)(?=[A-Z][a-z]?)|\B[A-Z]/, '_\&') =~ /_*(.*)/
  return $+.downcase
end

#to_constConstant

Convert constant name to constant

“FooBar::Baz”.to_const => FooBar::Baz

Returns:

  • (Constant)

    Constant corresponding to given name or nil if no constant with that name exists



39
40
41
42
43
44
45
46
47
48
49
# File 'lib/nanite/util.rb', line 39

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

  constant = Object
  names.each do |name|
    # modified to return nil instead of raising an const_missing error
    constant = constant && constant.const_defined?(name) ? constant.const_get(name) : nil
  end
  constant
end

#to_const_pathString

Convert a constant name to a path, assuming a conventional structure.

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

Returns:

  • (String)

    Path to the file containing the constant named by receiver (constantized string), assuming a conventional structure.



27
28
29
# File 'lib/nanite/util.rb', line 27

def to_const_path
  snake_case.gsub(/::/, "/")
end