跳到內容 跳到搜尋

已格式化的範圍

方法
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 hash 中。請使用格式名稱為 hash 鍵和 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