Class: ActiveStorage::Filename
- Inherits:
-
Object
- Object
- ActiveStorage::Filename
- Includes:
- Comparable
- Defined in:
- app/models/active_storage/filename.rb
Overview
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.
Instance Method Summary collapse
- #<=>(other) ⇒ Object
- #as_json ⇒ Object
-
#base ⇒ Object
Filename.new(“racecar.jpg”).base # => “racecar”.
-
#extension ⇒ Object
Filename.new(“racecar.jpg”).extension # => “jpg”.
-
#extname ⇒ Object
Filename.new(“racecar.jpg”).extname # => “.jpg”.
-
#initialize(filename) ⇒ Filename
constructor
A new instance of Filename.
-
#sanitized ⇒ Object
Filename.new(“foo:bar.jpg”).sanitized # => “foo-bar.jpg” Filename.new(“foo/bar.jpg”).sanitized # => “foo-bar.jpg”.
- #to_json ⇒ Object
-
#to_s ⇒ Object
Returns the sanitized version of the filename.
Constructor Details
#initialize(filename) ⇒ Filename
Returns a new instance of Filename.
6 7 8 |
# File 'app/models/active_storage/filename.rb', line 6 def initialize(filename) @filename = filename end |
Instance Method Details
#<=>(other) ⇒ Object
46 47 48 |
# File 'app/models/active_storage/filename.rb', line 46 def <=>(other) to_s.downcase <=> other.to_s.downcase end |
#as_json ⇒ Object
38 39 40 |
# File 'app/models/active_storage/filename.rb', line 38 def as_json(*) to_s end |
#base ⇒ Object
Filename.new(“racecar.jpg”).base # => “racecar”
21 22 23 |
# File 'app/models/active_storage/filename.rb', line 21 def base File.basename(@filename, extname) end |
#extension ⇒ Object
Filename.new(“racecar.jpg”).extension # => “jpg”
16 17 18 |
# File 'app/models/active_storage/filename.rb', line 16 def extension extname.from(1) end |
#extname ⇒ Object
Filename.new(“racecar.jpg”).extname # => “.jpg”
11 12 13 |
# File 'app/models/active_storage/filename.rb', line 11 def extname File.extname(@filename) end |
#sanitized ⇒ Object
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.
29 30 31 |
# File 'app/models/active_storage/filename.rb', line 29 def sanitized @filename.encode(Encoding::UTF_8, invalid: :replace, undef: :replace, replace: "�").strip.tr("\u{202E}%$|:;/\t\r\n\\", "-") end |
#to_json ⇒ Object
42 43 44 |
# File 'app/models/active_storage/filename.rb', line 42 def to_json to_s end |
#to_s ⇒ Object
Returns the sanitized version of the filename.
34 35 36 |
# File 'app/models/active_storage/filename.rb', line 34 def to_s sanitized.to_s end |