【问题标题】:Does rails have an opposite of 'humanize' for strings?Rails 是否与字符串的“人性化”相反?
【发布时间】: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


【解决方案1】:

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
  • 导轨 > 5 Employee salary".parameterize(separator: "_") # => employee_salary

【讨论】:

  • 比猴子修补String类简单得多
  • @giladbu 但这在以下情况下不起作用。 “author_id”.humanize 返回“作者”“作者”.parameterize.underscore 返回“作者”
  • 这可以通过将所需的分隔字符(在本例中为下划线)作为参数传递给parameterize 来更简单地完成。例如:"Employee Salary".parameterize("_")
  • 小更新。这种形式的参数传递很快就会被弃用。我们现在应该使用 'Employee Salary'.parameterize(separator: '_') 不是那么短,而是更清晰。
【解决方案2】:

http://as.rubyonrails.org/classes/ActiveSupport/CoreExtensions/String/Inflections.html 中,您有一些用于美化和取消美化字符串的方法。

【讨论】:

    【解决方案3】:

    Rail API 中似乎没有任何此类方法。但是,我确实发现这篇博文提供了一个(部分)解决方案:http://rubyglasses.blogspot.com/2009/04/dehumanizing-rails.html

    【讨论】:

      猜你喜欢
      • 2015-09-01
      • 2011-10-07
      • 1970-01-01
      • 1970-01-01
      • 2016-08-10
      • 1970-01-01
      • 2015-04-04
      • 2013-12-16
      相关资源
      最近更新 更多