Rails有没有一个与字符串的“humanize”相反的方法?

68

Rails为字符串添加了一个humanize()方法,其工作原理如下(来自Rails RDoc):

"employee_salary".humanize # => "Employee salary"
"author_id".humanize       # => "Author"

我希望反过来处理。我有一个用户输入的“漂亮”字符串,我想要将其“去人性化”以便写入模型属性:

"Employee salary"       # => employee_salary
"Some Title: Sub-title" # => some_title_sub_title

Rails有提供任何相关的帮助吗?

更新

与此同时,我已经将以下内容添加到app/controllers/application_controller.rb文件中:

class String
  def dehumanize
    self.downcase.squish.gsub( /\s/, '_' )
  end
end

有更好的位置可以放置吗?

解决方案

感谢 fd 提供的 链接。我已经按照该链接推荐的方法进行了实现。在我的 config/initializers/infections.rb 文件末尾添加了以下内容:

module ActiveSupport::Inflector
  # does the opposite of humanize ... mostly.
  # Basically does a space-substituting .underscore
  def dehumanize(the_string)
    result = the_string.to_s.dup
    result.downcase.gsub(/ +/,'_')
  end
end

class String
  def dehumanize
    ActiveSupport::Inflector.dehumanize(self)
  end
end

61
我对方法调用 dehumanize(self) 感到奇怪地不安... - zetetic
5
我尝试幽默一下:“grin”。我也考虑过用“.alienate(self)”来表示,不过我还是决定遵循惯例。 - Taryn East
4
还有 config/initializers/infections.rb :D - Ola Tuvesson
3个回答

150

string.parameterize.underscore会给你相同的结果。

"Employee salary".parameterize.underscore       # => employee_salary
"Some Title: Sub-title".parameterize.underscore # => some_title_sub_title

或者你也可以使用稍微更简洁一些的 .parameterize(separator: '_')(感谢 @danielricecodes)

  • Rails < 5 "员工薪水".parameterize("_") # => 员工薪水
  • Rails > 5 "员工薪水".parameterize(separator: "_") # => 员工薪水

2
比猴子补丁字符串类要简单得多。 - Alexis Perrier
1
@giladbu 但是在以下情况下这无法工作。 "author_id".humanize 返回 '作者' "Author".parameterize.underscore 返回 'author' - Kamesh
8
可以通过将所需的分隔符(在本例中为下划线)作为参数传递给 parameterize 方法来更简单地完成此操作。例如:"Employee Salary".parameterize("_") - danielricecodes
1
一个小更新。这种形式的参数传递很快就会被弃用。我们现在应该使用'Employee Salary'.parameterize(separator: '_'),虽然不太短,但更清晰易懂。 - Gaurav Shetty

3

2

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接