如何将 Ruby 类名转换为下划线分隔的符号?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5622435/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do I convert a Ruby class name to a underscore-delimited symbol?
提问by Josh Glover
How can I programmatically turn a class name, FooBar, into a symbol, :foo_bar? e.g. something like this, but that handles camel case properly?
如何以编程方式将类名FooBar, 转换为符号:foo_bar?例如像这样的东西,但是可以正确处理驼峰事件?
FooBar.to_s.downcase.to_sym
回答by kikito
Rails comes with a method called underscorethat will allow you to transform CamelCased strings into underscore_separated strings. So you might be able to do this:
Rails 附带了一个名为的方法,该方法underscore允许您将 CamelCased 字符串转换为 underscore_separated 字符串。所以你可以这样做:
FooBar.name.underscore.to_sym
But you will have to install ActiveSupport just to do that, as ipsum says.
但是,正如 ipsum 所说,您必须安装 ActiveSupport 才能做到这一点。
If you don't want to install ActiveSupport just for that, you can monkey-patch underscoreinto Stringyourself (the underscore function is defined in ActiveSupport::Inflector):
如果你不想安装的ActiveSupport只是,你就可以猴子补丁underscore到String自己(下划线函数中定义的ActiveSupport ::变形器):
class String
def underscore
word = self.dup
word.gsub!(/::/, '/')
word.gsub!(/([A-Z]+)([A-Z][a-z])/,'_')
word.gsub!(/([a-z\d])([A-Z])/,'_')
word.tr!("-", "_")
word.downcase!
word
end
end
回答by ipsum
first: gem install activesupport
第一: gem install activesupport
require 'rubygems'
require 'active_support'
"FooBar".underscore.to_sym
回答by Louis Sayers
Here's what I went for:
这是我的目的:
module MyModule
module ClassMethods
def class_to_sym
name_without_namespace = name.split("::").last
name_without_namespace.gsub(/([^\^])([A-Z])/,'_').downcase.to_sym
end
end
def self.included(base)
base.extend(ClassMethods)
end
end
class ThisIsMyClass
include MyModule
end
ThisIsMyClass.class_to_sym #:this_is_my_class

