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 提供的 链接。我已经按照该链接推荐的方法进行了实现。在我的 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)
感到奇怪地不安... - zetetic