轨道是否与字符串“人性化”相反?


67

Railshumanize()为字符串添加了一种方法,该方法的工作方式如下(来自Rails RDoc):

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

我想走另一条路。我有一个来自用户的“漂亮”输入,我想对其进行“去人性化”以写入模型的属性:

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

导轨对此有帮助吗?

更新资料

同时,我在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

56
我对方法调用感到不安dehumanize(self)...
10年

4
咧开嘴我的幽默...;)我也考虑过“ .alienate(self)”,但以为我会遵守惯例。
Taryn East,

4
还config / initializers / * infections * .rb:D
Ola Tuvesson

Answers:


145

string.parameterize.underscore会给你同样的结果

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

或者您也可以使用更简洁的代码(感谢@danielricecodes)。

  • 滑轨<5 Employee salary".parameterize("_") # => employee_salary
  • 导轨> 5 Employee salary".parameterize(separator: "_") # => employee_salary

2
比猴子修补String类简单得多
Alexis Perrier

1
@giladbu,但这在以下情况下不起作用。“ author_id” .humanize返回'作者'“ Author” .parameterize.underscore返回'作者'
Kamesh 2015年

8
通过将所需的分隔字符(在本例中为下划线)作为参数传递,可以更简单地完成此操作parameterize。例如:"Employee Salary".parameterize("_")
danielricecodes

1
较小的更新。这种形式的参数传递将很快被弃用。现在我们应该使用'Employee Salary'.parameterize(separator:'_')而不是那么短,但是要清晰得多。
Gaurav Shetty,


By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.