跳至内容 跳至搜索

带格式的范围

方法
T

常量

RANGE_FORMATS = { db: -> (start, stop) do if start && stop case start when String then "BETWEEN '#{start}' AND '#{stop}'" else "BETWEEN '#{start.to_fs(:db)}' AND '#{stop.to_fs(:db)}'" end elsif start case start when String then ">= '#{start}'" else ">= '#{start.to_fs(:db)}'" end elsif stop case stop when String then "<= '#{stop}'" else "<= '#{stop.to_fs(:db)}'" end end end }
 

实例公共方法

to_formatted_s(format = :default)

别名:to_fs

to_fs(format = :default)

将范围转换为格式化的字符串。请参阅 RANGE_FORMATS 获取预定义的格式。

此方法是 to_formatted_s 的别名。

range = (1..100)           # => 1..100

range.to_s                 # => "1..100"
range.to_fs(:db)           # => "BETWEEN '1' AND '100'"

range = (1..)              # => 1..
range.to_fs(:db)           # => ">= '1'"

range = (..100)            # => ..100
range.to_fs(:db)           # => "<= '100'"

to_fs 添加您自己的范围格式

您可以向 Range::RANGE_FORMATS 哈希中添加您自己的格式。使用格式名称作为哈希键和 Proc 实例。

# config/initializers/range_formats.rb
Range::RANGE_FORMATS[:short] = ->(start, stop) { "Between #{start.to_fs(:db)} and #{stop.to_fs(:db)}" }
也被称为:to_formatted_s
# File activesupport/lib/active_support/core_ext/range/conversions.rb, line 51
def to_fs(format = :default)
  if formatter = RANGE_FORMATS[format]
    formatter.call(self.begin, self.end)
  else
    to_s
  end
end