Get class / module name

Is there a better way to get the class / module name: Cfrom A::B::C, Bfrom A::B::Cand Afrom A::B::C. The following code uses string and split to get "Stegosaurus"from Cowsay::Character::Stegosaurus, how to delete a string and split?

require 'cowsay'
x = Cowsay.random_character().class
x.name.split("::")[2]
require 'cowsay'
true
x = Cowsay.random_character().class
Cowsay::Character::Stegosaurus
x.name.split("::")[2]
"Stegosaurus"

thank

+4
source share
1 answer

I don't think there is anything to handle this in the main / standard library.

As an alternative to custom writing methods, there is always activesupport:

require 'active_support/core_ext/string/inflections'
Cowsay::Character::Stegosaurus.name.demodulize
#=> "Stegosaurus"
Cowsay::Character::Stegosaurus.name.deconstantize
#=> "Cowsay::Character"

These methods are implemented as follows:

def demodulize(path)
  path = path.to_s
  if i = path.rindex('::')
    path[(i+2)..-1]
  else
    path
  end
end

def deconstantize(path)
  path.to_s[0, path.rindex('::') || 0] # implementation based on the one in facets' Module#spacename
end

Check out the docs if you are interested in other methods.

Concerning

A From A::B::C

require activesupport, Module, parent

require 'active_support'
Cowsay::Character::Stegosaurus.parent
#=> Cowsay

, activesupport , .

+4

Source: https://habr.com/ru/post/1658627/


All Articles