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

时间:2010-05-14 16:22:59

标签: ruby-on-rails

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

有没有更好的地方呢?

解决方案

感谢fdlink。我已经实现了那里推荐的解决方案。在我的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

3 个答案:

答案 0 :(得分:142)

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

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

或者您也可以使用稍微简洁一点(感谢@danielricecodes)。

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

答案 1 :(得分:3)

Rail API中似乎没有任何此类方法。但是,我确实发现这篇博文提供了(部分)解决方案:http://rubyglasses.blogspot.com/2009/04/dehumanizing-rails.html

答案 2 :(得分:1)

http://as.rubyonrails.org/classes/ActiveSupport/CoreExtensions/String/Inflections.html中,你有一些方法用来美化和取消美化字符串。