简体   繁体   English

获取类/模块名称

[英]Get class/module name

Is there a better way to get class/module name viz, C from A::B::C , B from A::B::C , and A From A::B::C .有没有更好的方式来获得类/模块的名称即, CA::B::CBA::B::C ,和AA::B::C The following code uses string and split to get "Stegosaurus" from Cowsay::Character::Stegosaurus , How to do away with string and split?以下代码使用字符串和拆分从Cowsay::Character::Stegosaurus获取"Stegosaurus" ,如何Cowsay::Character::Stegosaurus字符串和拆分?

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"

I don't think there's anything for handling this in core/standard library.我认为在核心/标准库中没有任何东西可以处理这个问题。

As an alternative to custom written methods there is always activesupport :作为自定义编写方法的替代方案,总是有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

Take a look into docs if interested in more methods.如果对更多方法感兴趣,请查看文档

As to至于

A From A::B::C AA::B::C

If you'd require the whole activesupport , you'd get bunch of Module methods, including parent :如果你require整个activesupport ,你会得到一堆Module方法,包括parent

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

If you're not going to use it extensively, I recommend to just grab the needed methods from activesupport and put it into some helper, because loading it whole might be an overkill.如果您不打算广泛使用它,我建议您只从activesupport获取所需的方法并将其放入一些帮助程序中,因为将其全部加载可能是一种矫枉过正。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM