对于字符串,rails是否与'humanize'相反?

irk*_*der 65 ruby-on-rails

Rails humanize()为字符串添加了一个方法,如下所示(来自Rails RDoc):

"employee_salary".humanize # => "Employee salary"
"author_id".humanize       # => "Author"
Run Code Online (Sandbox Code Playgroud)

我想走另一条路.我有一个用户的"漂亮"输入,我想要"去人性化"来写入模型的属性:

"Employee salary"       # => employee_salary
"Some Title: Sub-title" # => some_title_sub_title
Run Code Online (Sandbox Code Playgroud)

rails是否包含任何帮助?

更新

在此期间,我将以下内容添加到app/controllers/application_controller.rb:

class String
  def dehumanize
    self.downcase.squish.gsub( /\s/, '_' )
  end
end
Run Code Online (Sandbox Code Playgroud)

还有更好的地方吗?

谢谢,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
Run Code Online (Sandbox Code Playgroud)

gil*_*dbu 144

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

"Employee salary".parameterize.underscore       # => employee_salary
"Some Title: Sub-title".parameterize.underscore # => some_title_sub_title
Run Code Online (Sandbox Code Playgroud)

或者您也可以使用稍微简洁的(感谢@danielricecodes).

"Employee salary".parameterize.underscore       # => employee_salary
"Some Title: Sub-title".parameterize.underscore # => some_title_sub_title
Run Code Online (Sandbox Code Playgroud)

  • 这可以通过将所需的分隔字符(在本例中为下划线)作为参数传递给`parameterize`来更简单地完成.例如:"员工薪水".parameterize("_")` (8认同)
  • 比猴子修补String类简单得多 (2认同)