3

我需要一种通用的方法来将类名转换为带下划线的小写。例如,我希望将类名转换NewUserBatchnew_user_batch. 这该怎么做?

4

3 回答 3

7

Underscore.

>> 'NewUserBatch'.underscore
=> "new_user_batch"

它包含在 Rails 中,所以如果你不使用它,你可以参考它的源代码。

def underscore(camel_cased_word)
  word = camel_cased_word.to_s.dup
  word.gsub!(%r::/, '/')
  word.gsub!(%r(?:([A-Za-z\d])|^)(#{inflections.acronym_regex})(?=\b|[^a-z])/) { "#{$1}#{$1 && '_'}#{$2.downcase}" }
  word.gsub!(%r([A-Z\d]+)([A-Z][a-z])/,'\1_\2')
  word.gsub!(%r([a-z\d])([A-Z])/,'\1_\2')
  word.tr!("-", "_")
  word.downcase!
  word
end
于 2012-10-18T09:02:53.913 回答
2

在简单的情况下,你只有非命名空间的类名,你可以使用这个 oneliner:

编辑:更新了积极的前瞻性断言(感谢@vladr)

"MYRubyClassName".gsub(/(.)([A-Z](?=[a-z]))/,'\1_\2').downcase

# => "my_ruby_class_name"

这会找到跟随另一个字符的所有大写字符,然后是一个小写字符,在它之前插入下划线,然后将所有内容小写。

于 2012-10-18T09:31:12.870 回答
0

Also a nice tip: to find if you know INPUT (NewUserBatch) and OUTPUT (new_user_batch) use the following method

"NewUserBatch".find_method("new_user_batch")
于 2012-10-18T10:05:20.627 回答