以下是 Rails 1.1 发布以来添加到 Rails 1.2 ActiveSupport 的一些较小但显著的功能。(由 Joshua Sierles 编译)。
Module#unloadable
标记每次请求后需要卸载的常量。示例
CONFIG.unloadable
Module#alias_attribute
克隆类属性,包括它们的 getter、setter 和查询方法。示例
class Email < ActiveRecord::Base
alias_attribute :subject, :title
end
e = Email.find(1)
e.title # => "Superstars"
e.subject # => "Superstars"
e.subject? # => true
e.subject = "Megastars"
e.title # => "Megastars"
Enumerable#sum
根据数组元素计算和。示例
[1, 2, 3].sum
payments.sum { |p| p.price * p.tax_rate }
payments.sum(&:price)
This replaces: payments.inject(0) { |sum, p| sum + p.price }
Array#to_s(:db)
生成以逗号分隔的 ID 列表。示例
Purchase.find(:all, :conditions => "product_id IN (#{shops.products.to_s(:db)})"
Module#alias_method_chain
封装常用模式
alias_method :foo_without_feature, :foo
alias_method :foo, :foo_with_feature
With alias_method_chain:
alias_method_chain :foo, :feature
Array#split
按值或块将数组划分为一个或多个子数组。示例
[1, 2, 3, 4, 5].split(3) => [[1, 2], [4, 5]]
(1..10).to_a.split { |i| i % 3 == 0 } # => [[1, 2], [4, 5], [7, 8], [10]]
Hash.from_xml(string)
从 XML 字符串创建一个哈希表,尽可能转换其元素类型。示例
Hash.from_xml <<-EOT
<note>
<title>This is a note</title>
<created-at type="date">2004-10-10</created-at>
</note>
EOT
...would return:
{ :note => { :title => "This is a note", :created_at => Date.new(2004, 10, 10) } }
Builder 包已升级到 2.0 版本。更改包括
-- UTF-8 characters in data are now correctly translated to their XML equivalents
-- Attribute values are now escaped by default