Railshumanize()
为字符串添加了一种方法,该方法的工作方式如下(来自Rails RDoc):
"employee_salary".humanize # => "Employee salary"
"author_id".humanize # => "Author"
我想走另一条路。我有一个来自用户的“漂亮”输入,我想对其进行“去人性化”以写入模型的属性:
"Employee salary" # => employee_salary
"Some Title: Sub-title" # => some_title_sub_title
导轨对此有帮助吗?
更新资料
同时,我在app / controllers / application_controller.rb中添加了以下内容:
class String
def dehumanize
self.downcase.squish.gsub( /\s/, '_' )
end
end
有没有更好的放置位置?
解
谢谢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
dehumanize(self)
...