2017-07-24 13:05:15 -04:00
|
|
|
|
# Encapsulates a string representing a filename to provide convenience access to parts of it and a sanitized version.
|
|
|
|
|
# This is what's returned by `ActiveStorage::Blob#filename`. A Filename instance is comparable so it can be used for sorting.
|
2017-07-06 05:33:29 -04:00
|
|
|
|
class ActiveStorage::Filename
|
2017-06-30 13:12:58 -04:00
|
|
|
|
include Comparable
|
|
|
|
|
|
|
|
|
|
def initialize(filename)
|
|
|
|
|
@filename = filename
|
|
|
|
|
end
|
|
|
|
|
|
2017-07-24 13:05:15 -04:00
|
|
|
|
# Filename.new("racecar.jpg").extname # => ".jpg"
|
2017-06-30 13:12:58 -04:00
|
|
|
|
def extname
|
|
|
|
|
File.extname(@filename)
|
|
|
|
|
end
|
|
|
|
|
|
2017-07-24 13:05:15 -04:00
|
|
|
|
# Filename.new("racecar.jpg").extension # => "jpg"
|
2017-06-30 13:12:58 -04:00
|
|
|
|
def extension
|
|
|
|
|
extname.from(1)
|
|
|
|
|
end
|
|
|
|
|
|
2017-07-24 13:05:15 -04:00
|
|
|
|
# Filename.new("racecar.jpg").base # => "racecar"
|
2017-06-30 13:12:58 -04:00
|
|
|
|
def base
|
|
|
|
|
File.basename(@filename, extname)
|
|
|
|
|
end
|
|
|
|
|
|
2017-07-24 13:05:15 -04:00
|
|
|
|
# Filename.new("foo:bar.jpg").sanitized # => "foo-bar.jpg"
|
|
|
|
|
# Filename.new("foo/bar.jpg").sanitized # => "foo-bar.jpg"
|
|
|
|
|
#
|
|
|
|
|
# ...and any other character unsafe for URLs or storage is converted or stripped.
|
2017-06-30 13:12:58 -04:00
|
|
|
|
def sanitized
|
|
|
|
|
@filename.encode(Encoding::UTF_8, invalid: :replace, undef: :replace, replace: "<EFBFBD>").strip.tr("\u{202E}%$|:;/\t\r\n\\", "-")
|
|
|
|
|
end
|
|
|
|
|
|
2017-07-24 13:05:15 -04:00
|
|
|
|
# Returns the sanitized version of the filename.
|
2017-06-30 13:12:58 -04:00
|
|
|
|
def to_s
|
|
|
|
|
sanitized.to_s
|
|
|
|
|
end
|
|
|
|
|
|
|
|
|
|
def <=>(other)
|
|
|
|
|
to_s.downcase <=> other.to_s.downcase
|
|
|
|
|
end
|
|
|
|
|
end
|