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)
归档时间: |
|
查看次数: |
15853 次 |
最近记录: |