class ActiveStorage::Filename
A Filename instance is returned by ActiveStorage::Blob#filename, and is comparable so it can be used for sorting.
Encapsulates a string representing a filename to provide convenient access to parts of it and sanitization.
def <=>(other)
def <=>(other) to_s.downcase <=> other.to_s.downcase end
def as_json(*)
def as_json(*) to_s end
def base
ActiveStorage::Filename.new("racecar").base # => "racecar"
ActiveStorage::Filename.new("racecar.jpg").base # => "racecar"
Returns the part of the filename preceding any extension.
def base File.basename @filename, extension_with_delimiter end
def extension_with_delimiter
ActiveStorage::Filename.new("racecar").extension_with_delimiter # => ""
ActiveStorage::Filename.new("racecar.jpg").extension_with_delimiter # => ".jpg"
beginning) with the dot that precedes it. If the filename has no extension, an empty string is returned.
Returns the extension of the filename (i.e. the substring following the last dot, excluding a dot at the
def extension_with_delimiter File.extname @filename end
def extension_without_delimiter
ActiveStorage::Filename.new("racecar").extension_without_delimiter # => ""
ActiveStorage::Filename.new("racecar.jpg").extension_without_delimiter # => "jpg"
the beginning). If the filename has no extension, an empty string is returned.
Returns the extension of the filename (i.e. the substring following the last dot, excluding a dot at
def extension_without_delimiter extension_with_delimiter.from(1).to_s end
def initialize(filename)
def initialize(filename) @filename = filename end
def sanitized
ActiveStorage::Filename.new("foo/bar.jpg").sanitized # => "foo-bar.jpg"
ActiveStorage::Filename.new("foo:bar.jpg").sanitized # => "foo-bar.jpg"
Returns the sanitized filename.
def sanitized @filename.encode(Encoding::UTF_8, invalid: :replace, undef: :replace, replace: "�").strip.tr("\u{202E}%$|:;/\t\r\n\\", "-") end
def to_json
def to_json to_s end
def to_s
def to_s sanitized.to_s end
def wrap(filename)
Returns a Filename instance based on the given filename. If the filename is a Filename, it is
def wrap(filename) filename.kind_of?(self) ? filename : new(filename) end