跳至内容 跳至搜索

Active Storage Filename

封装一个代表文件名字符串的对象,以便于访问其各个部分和进行清理。`ActiveStorage::Blob#filename` 方法会返回一个 `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 73
def <=>(other)
  to_s.downcase <=> other.to_s.downcase
end

as_json(*)

# File activestorage/app/models/active_storage/filename.rb, line 69
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()

返回清理过的文件名版本。

也别名为: to_str
# File activestorage/app/models/active_storage/filename.rb, line 64
def to_s
  sanitized.to_s
end

to_str()

别名: to_s