跳至内容 跳至搜索

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,则直接返回。如果它是 String,则将其传递给 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