Rails 是否与字符串的“人性化"相反? [英] Does rails have an opposite of 'humanize' for strings?

查看:33
本文介绍了Rails 是否与字符串的“人性化"相反?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Rails adds a humanize() method for strings that works as follows (from the Rails RDoc):

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

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

I want to go the other way. I have "pretty" input from a user that I want to 'de-humanize' for writing to a model's attribute:

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

rails 是否提供任何帮助?

Does rails include any help for this?

与此同时,我在 app/controllers/application_controller.rb 中添加了以下内容:

In the meantime, I added the following to app/controllers/application_controller.rb:

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

有没有更好的地方放置它?

Is there a better place to put it?

感谢fd,感谢链接.我已经实施了那里推荐的解决方案.在我的 config/initializers/infections.rb 中,我在最后添加了以下内容:

Thanks, fd, for the link. I've implemented the solution recommended there. In my config/initializers/infections.rb, I added the following at the end:

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

推荐答案

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

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

或者你也可以使用更简洁的(感谢@danielricecodes).

or you can also use which is slightly more succinct (thanks @danielricecodes).

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

这篇关于Rails 是否与字符串的“人性化"相反?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆