Class: Zaru
- Inherits:
-
Object
- Object
- Zaru
- Defined in:
- lib/zaru.rb
Constant Summary collapse
- CHARACTER_FILTER =
/[\x00-\x1F\/\\:\*\?\"<>\|]/u
- UNICODE_WHITESPACE =
/[[:space:]]+/u
- WINDOWS_RESERVED_NAMES =
%w{CON PRN AUX NUL COM1 COM2 COM3 COM4 COM5 COM6 COM7 COM8 COM9 LPT1 LPT2 LPT3 LPT4 LPT5 LPT6 LPT7 LPT8 LPT9}
- FALLBACK_FILENAME =
'file'
Class Method Summary collapse
-
.sanitize!(filename, options = {}) ⇒ Object
convenience method.
Instance Method Summary collapse
-
#initialize(filename, options = {}) ⇒ Zaru
constructor
A new instance of Zaru.
-
#normalize ⇒ Object
strip whitespace on beginning and end collapse intra-string whitespace into single spaces.
-
#sanitize ⇒ Object
remove bad things! - remove characters that aren’t allowed cross-OS - don’t allow certain special filenames (issue on Windows) - don’t allow filenames to start with a dot - don’t allow empty filenames.
- #to_s ⇒ Object
-
#truncate ⇒ Object
cut off at 255 characters optionally provide a padding, which is useful to make sure there is room to add a file extension later.
Constructor Details
#initialize(filename, options = {}) ⇒ Zaru
Returns a new instance of Zaru.
12 13 14 15 |
# File 'lib/zaru.rb', line 12 def initialize(filename, = {}) @padding = [:padding] || 0 @raw = filename.to_s.freeze end |
Class Method Details
.sanitize!(filename, options = {}) ⇒ Object
convenience method
45 46 47 |
# File 'lib/zaru.rb', line 45 def self.sanitize!(filename, = {}) new(filename, ).to_s end |
Instance Method Details
#normalize ⇒ Object
strip whitespace on beginning and end collapse intra-string whitespace into single spaces
19 20 21 |
# File 'lib/zaru.rb', line 19 def normalize @normalized ||= @raw.strip.gsub(UNICODE_WHITESPACE,' ') end |
#sanitize ⇒ Object
remove bad things!
-
remove characters that aren’t allowed cross-OS
-
don’t allow certain special filenames (issue on Windows)
-
don’t allow filenames to start with a dot
-
don’t allow empty filenames
28 29 30 31 |
# File 'lib/zaru.rb', line 28 def sanitize @sanitized ||= filter(normalize.gsub(CHARACTER_FILTER,'')) end |
#to_s ⇒ Object
40 41 42 |
# File 'lib/zaru.rb', line 40 def to_s truncate end |
#truncate ⇒ Object
cut off at 255 characters optionally provide a padding, which is useful to make sure there is room to add a file extension later
36 37 38 |
# File 'lib/zaru.rb', line 36 def truncate @truncated ||= sanitize.chars.to_a.slice(0..254-@padding).join end |