开启掘金成长之旅!这是我参与「掘金日新计划 · 2 月更文挑战」的第 25 天,点击查看活动详情”
六、ActiveSupport
ActiveSupport 是一组类库,他为 Rails 应用提供了许多实用的扩展功能,有些是对 Ruby 基本类的扩展。
字符串的扩展
ActiveSupport 给字符串增加了一些方法,如单复数抓换的方法:pluralize 和 singularize。另外还有便于子字符串操作的方法:at、first、form、last 和 to,用于类型转换的 to_data 和 to_time 方法等,比较常用的方法作用如下:
- at(position):返回position 位置的字符,例如
"hello".at(0) #=> "h" - first(limit=1): 返回从第一个字符开始的limit个字符,例如
"hello".first #=> "h","hello".first(2) #=> "he" - from(position):返回字符串开始剩余的所有字符,例如
"hello".from(0) #=> "hello","hello".from(2) #=> "llo","hello".from(10) #=> nil - last(limit=1):返回倒数的limit长度的部分字符串,例如
"hello".last #=> "o","hello".last(2) #=> "lo","hello".last(10) #=> "hello" - to(position):与 from 方法作用相反,返回从第一个字符至 position 位置的字符,如
"hello".to(0) #=> "h","hello".to(2) #=> "hel","hello".to(10) #=> "hello" - to_date:转换为时间Date类型
- to_time:转换为时间Time类型
- camelize:将按下划线分割字符串为首字母大写的形式,例如
"hello_world".camelize #=> "HelloWorld" - humanize:将第一个字符大写,下划线转为空格,例如
"hello_world".humanize #=> "Hello world" - titleize:将每个单词的第一个字母大写,下划线转为空格,通常给用户标题显示,例如
"hello_world".humanize #=> "Hello World"
对时间 date 类的扩展
ActiveSupport 对 date 类扩展的方法如下:
扩展类方法有:
- beginning_of_week:返回一个星期的第一天,返回当前线程所在地域的星期的第一天,如果没有设置,返回config文件中设置的一个星期的第一天,如果配置文件中也没有设置,就返回monday。
- beginning_of_week=(week_start):设置当前线程的星期的第一天。
- find_beginning_of_week!(week_start):返回一个星期开始的第一天的symbol,例如,:monday。
- yesterday:当前日期的昨天
- tomorrow:当前日期的明天
- current:如果设置了时区,就会时区的今天,否则返回Date.today。
扩展的实例方法有:
- ago(seconds):多少秒之前的时间
- since(seconds):多少秒之后的时间,别名:alias :in :since
- beginning_of_day:一天开始的时间,0分0秒。别名 alias :midnight :beginning_of_day,alias :at_midnight :beginning_of_day,alias :at_beginning_of_day :beginning_of_day
- end_of_day:一天结束的时间,23小时59分59秒。
- change(options):改变日期的某个部分,options参数是字典格式,:year,:month,:day分别代表年,月,日。
对数字的扩展
ActiveSupport 为 Fixnum 类加上了 even? 和 odd? 两个方法,用于判断数字的奇偶性。
还有一组字节转换计算的方法,如:
10.bytes => 10
10.kilobytes => 10240
10.megabytes => 10485760
10.gigabytes => 10737418240
10.terabytes => 10995116277760
还有一组时间转换的方法,基本单位为秒,如:
10.minutes => 600
10.hours => 3600
10.days => 864000
10.weeks => 6048000
10.fornights => 12096000
10.months => 25920000
10.years => 315576000
ActiveSupport 的扩展还有很多。