跳至內容 跳至搜尋

Active Storage 檔案名稱

封裝表示檔案名稱的字串,以提供方便訪問其各個部分和進行清理。 Filename 實例由 ActiveStorage::Blob#filename 返回,並且可比較,因此可用於排序。

方法
#
A
B
E
N
S
T
W
包含的模組

類別公開方法

new(filename)

# File activestorage/app/models/active_storage/filename.rb, line 18
def initialize(filename)
  @filename = filename
end

wrap(filename)

根據給定的檔案名稱返回一個 Filename 實例。如果檔案名稱是 Filename,則不修改地返回它。如果它是 字串,則將其傳遞給 ActiveStorage::Filename.new

# File activestorage/app/models/active_storage/filename.rb, line 13
def wrap(filename)
  filename.kind_of?(self) ? filename : new(filename)
end

實例公開方法

<=>(other)

# File activestorage/app/models/active_storage/filename.rb, line 72
def <=>(other)
  to_s.downcase <=> other.to_s.downcase
end

as_json(*)

# File activestorage/app/models/active_storage/filename.rb, line 68
def as_json(*)
  to_s
end

base()

返回檔案名稱中任何副檔名之前的部分。

ActiveStorage::Filename.new("racecar.jpg").base # => "racecar"
ActiveStorage::Filename.new("racecar").base     # => "racecar"
ActiveStorage::Filename.new(".gitignore").base  # => ".gitignore"
# File activestorage/app/models/active_storage/filename.rb, line 27
def base
  File.basename @filename, extension_with_delimiter
end

extension()

extension_with_delimiter()

返回檔案名稱的副檔名(即最後一個點之後的子字串,不包括開頭的點),以及它前面的點。如果檔案名稱沒有副檔名,則返回空字串。

ActiveStorage::Filename.new("racecar.jpg").extension_with_delimiter # => ".jpg"
ActiveStorage::Filename.new("racecar").extension_with_delimiter     # => ""
ActiveStorage::Filename.new(".gitignore").extension_with_delimiter  # => ""
# File activestorage/app/models/active_storage/filename.rb, line 37
def extension_with_delimiter
  File.extname @filename
end

extension_without_delimiter()

返回檔案名稱的副檔名(即最後一個點之後的子字串,不包括開頭的點)。如果檔案名稱沒有副檔名,則返回空字串。

ActiveStorage::Filename.new("racecar.jpg").extension_without_delimiter # => "jpg"
ActiveStorage::Filename.new("racecar").extension_without_delimiter     # => ""
ActiveStorage::Filename.new(".gitignore").extension_without_delimiter  # => ""
也稱為:extension
# File activestorage/app/models/active_storage/filename.rb, line 47
def extension_without_delimiter
  extension_with_delimiter.from(1).to_s
end

sanitized()

返回已清理的檔案名稱。

ActiveStorage::Filename.new("foo:bar.jpg").sanitized # => "foo-bar.jpg"
ActiveStorage::Filename.new("foo/bar.jpg").sanitized # => "foo-bar.jpg"

被認為不安全儲存的字元(例如 , $ 和 RTL 覆蓋字元)將被破折號取代。

# File activestorage/app/models/active_storage/filename.rb, line 59
def sanitized
  @filename.encode(Encoding::UTF_8, invalid: :replace, undef: :replace, replace: "�").strip.tr("\u{202E}%$|:;/<>?*\"\t\r\n\\", "-")
end

to_s()

返回檔案名稱的已清理版本。

# File activestorage/app/models/active_storage/filename.rb, line 64
def to_s
  sanitized.to_s
end