diff options
author | Rafael Mendonça França <rafaelmfranca@gmail.com> | 2017-07-31 15:21:22 -0400 |
---|---|---|
committer | Rafael Mendonça França <rafaelmfranca@gmail.com> | 2017-07-31 15:21:22 -0400 |
commit | 9330d01ada9ce6768d14c59b99cd3860e209737a (patch) | |
tree | e4328b4e59b52dae35241f835f786641d1ff8595 /activestorage/app/models/active_storage/filename.rb | |
parent | 0d58e7e478e79c2d6b2a39a4444d2a17a903b2a6 (diff) | |
parent | 3f4a7218a4a4923a0e7ce1b2eb0d2888ce30da58 (diff) | |
download | rails-9330d01ada9ce6768d14c59b99cd3860e209737a.tar.gz rails-9330d01ada9ce6768d14c59b99cd3860e209737a.tar.bz2 rails-9330d01ada9ce6768d14c59b99cd3860e209737a.zip |
Add 'activestorage/' from commit '3f4a7218a4a4923a0e7ce1b2eb0d2888ce30da58'
git-subtree-dir: activestorage
git-subtree-mainline: 0d58e7e478e79c2d6b2a39a4444d2a17a903b2a6
git-subtree-split: 3f4a7218a4a4923a0e7ce1b2eb0d2888ce30da58
Diffstat (limited to 'activestorage/app/models/active_storage/filename.rb')
-rw-r--r-- | activestorage/app/models/active_storage/filename.rb | 49 |
1 files changed, 49 insertions, 0 deletions
diff --git a/activestorage/app/models/active_storage/filename.rb b/activestorage/app/models/active_storage/filename.rb new file mode 100644 index 0000000000..35f4a8ac59 --- /dev/null +++ b/activestorage/app/models/active_storage/filename.rb @@ -0,0 +1,49 @@ +# 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. +class ActiveStorage::Filename + include Comparable + + def initialize(filename) + @filename = filename + end + + # Filename.new("racecar.jpg").extname # => ".jpg" + def extname + File.extname(@filename) + end + + # Filename.new("racecar.jpg").extension # => "jpg" + def extension + extname.from(1) + end + + # Filename.new("racecar.jpg").base # => "racecar" + def base + File.basename(@filename, extname) + end + + # 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. + def sanitized + @filename.encode(Encoding::UTF_8, invalid: :replace, undef: :replace, replace: "�").strip.tr("\u{202E}%$|:;/\t\r\n\\", "-") + end + + # Returns the sanitized version of the filename. + def to_s + sanitized.to_s + end + + def as_json(*) + to_s + end + + def to_json + to_s + end + + def <=>(other) + to_s.downcase <=> other.to_s.downcase + end +end |