【发布时间】:2011-02-19 14:48:36
【问题描述】:
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
【问题讨论】:
-
方法调用
dehumanize(self)... -
grin 我的幽默尝试...... ;) 我也考虑过“.alienate(self)”,但我认为我会坚持惯例。
-
还有 config/initializers/*infections*.rb :D
标签: ruby-on-rails