Active Support 是 Rails 核心擴展庫,擴充 Ruby 內建類別(Numeric, Time, String 等),提供大量實用方法,是 Rails 開發體驗流暢的關鍵基石。
20.bytes # => 20
20.kilobytes # => 20480
20.megabytes # => 20971520
20.gigabytes # => 21474836480
20.terabytes # => 21990232555520
20.minutes # => 1200
20.hours # => 72000
20.days # => 1728000
20.weeks # => 12096000
20.fortnights # => 24192000
20.months # => 51840000 (近似:30天/月)
20.years # => 630720000 (近似:365天/年)
5.even? # => false
5.odd? # => true
Time 類別新增豐富的相對時間計算與邊界方法:
now = Time.now
now.ago(3600) # 1小時前
now.at_beginning_of_day # 今天 00:00:00
now.at_beginning_of_week # 本週一 00:00:00
now.at_beginning_of_month # 本月1號 00:00:00
now.at_beginning_of_year # 1月1號 00:00:00
now.change(:hour => 13) # 今日 13:00:00
now.yesterday / now.tomorrow # 昨天/明天同一時間
now.last_month / now.next_month # 上/下個月同一天
now.months_ago(2) / months_since(2)
now.years_ago(2) / years_since(2)
now.seconds_since_midnight # 今日經過秒數
now.midnight # 今日 00:00:00 (同 at_beginning_of_day)
TimeZone 類別提供時區名稱、偏移量、標準時間/夏令時間轉換,支援 time_zone_select 表單輔助方法。
"cat".pluralize # => "cats"
"cats".pluralize # => "cats"
"erratum".pluralize # => "errata"
"cats".singularize # => "cat"
"errata".singularize # => "erratum"
"active_record".camelize # => "ActiveRecord"
"ActiveRecord".underscore # => "active_record"
"active_record".titleize # => "Active Record"
"ActiveRecord".demodulize # => "ActiveRecord" (移除模組前綴)
"admin/user".tableize # => "admin_users" (類別名→表名)
"admin_users".classify # => "Admin::User" (表名→類別名)
"user_name".humanize # => "User name" (欄位名→人類可讀)
" hello ".squish # => "hello" (移除首尾空白並壓縮中間多餘空白)
"hello".truncate(3) # => "hel..."
"hello".starts_with?("he") # => true
"hello".ends_with?("lo") # => true
[1,2,3].to_param # => "1/2/3" (路由參數序列化)
{:a => 1}.to_param # => "a=1" (查詢字串序列化)
[1,2,3].second # => 2 (取第二個元素)
[1,2,3].from(1) # => [2,3] (從索引1開始)
[1,2,3].to(1) # => [1,2] (到索引1結束)
[1,2,3].in_groups_of(2) # => [[1,2], [3,nil]] (分組)