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,link。我已经实现了那里推荐的解决方案。在我的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
答案 0 :(得分:142)
string.parameterize.underscore
会给你相同的结果
"Employee salary".parameterize.underscore # => employee_salary
"Some Title: Sub-title".parameterize.underscore # => some_title_sub_title
或者您也可以使用稍微简洁一点(感谢@danielricecodes)。
Employee salary".parameterize("_") # => employee_salary
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中,你有一些方法用来美化和取消美化字符串。