Class: ActiveStorage::Filename

Inherits:
Object
  • Object
show all
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

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_jsonObject



38
39
40
# File 'app/models/active_storage/filename.rb', line 38

def as_json(*)
  to_s
end

#baseObject

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

#extensionObject

Filename.new(“racecar.jpg”).extension # => “jpg”



16
17
18
# File 'app/models/active_storage/filename.rb', line 16

def extension
  extname.from(1)
end

#extnameObject

Filename.new(“racecar.jpg”).extname # => “.jpg”



11
12
13
# File 'app/models/active_storage/filename.rb', line 11

def extname
  File.extname(@filename)
end

#sanitizedObject

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_jsonObject



42
43
44
# File 'app/models/active_storage/filename.rb', line 42

def to_json
  to_s
end

#to_sObject

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