Class: FileInfo
- Inherits:
-
Object
show all
- Defined in:
- lib/file_info.rb,
lib/file_info/version.rb
Defined Under Namespace
Classes: UnknownEncodingError
Constant Summary
collapse
- MIME_TYPE_REGEX =
/^[^;]+/
- CHARSET_REGEX =
/charset=(\S+)/
- MIME_TYPE_ERROR_MESSAGE =
'You must install the "mime-types" gem to use FileInfo#mime_type'
- DEFAULT_MIME_TYPE =
'application/octet-stream'
- VERSION =
'0.5.1'
Instance Attribute Summary collapse
Class Method Summary
collapse
Instance Method Summary
collapse
Constructor Details
#initialize(output) ⇒ FileInfo
Returns a new instance of FileInfo.
17
18
19
|
# File 'lib/file_info.rb', line 17
def initialize(output)
@content_type = output.strip
end
|
Instance Attribute Details
#content_type ⇒ Object
Returns the value of attribute content_type.
15
16
17
|
# File 'lib/file_info.rb', line 15
def content_type
@content_type
end
|
Class Method Details
.load(filename) ⇒ Object
55
56
57
58
|
# File 'lib/file_info.rb', line 55
def self.load(filename)
raise ArgumentError, "File '#{filename}' does not exist." if !File.exists? filename
new `file --mime --brief #{Shellwords.escape(filename)}`
end
|
.parse(content) ⇒ Object
60
61
62
63
64
65
66
67
68
|
# File 'lib/file_info.rb', line 60
def self.parse(content)
file = Tempfile.new(rand.to_s, encoding: Encoding::ASCII_8BIT)
file.write(content)
file.rewind
new `file --mime --brief #{file.path}`
ensure
file.close
file.unlink
end
|
Instance Method Details
#charset ⇒ Object
45
46
47
|
# File 'lib/file_info.rb', line 45
def charset
@charset ||= (matches = content_type.match(CHARSET_REGEX)) ? matches[1] : 'binary'
end
|
#encoding ⇒ Object
49
50
51
52
53
|
# File 'lib/file_info.rb', line 49
def encoding
@encoding ||= ::Encoding.find(charset)
rescue ArgumentError => e
raise UnknownEncodingError, e.message
end
|
28
29
30
|
# File 'lib/file_info.rb', line 28
def media_type
@media_type ||= type.split('/')[0]
end
|
#mime_type ⇒ Object
36
37
38
39
40
41
42
43
|
# File 'lib/file_info.rb', line 36
def mime_type
@mime_type ||= begin
require 'mime/types' unless defined? MIME::Types
MIME::Types[type][0]
rescue LoadError
raise LoadError, MIME_TYPE_ERROR_MESSAGE
end
end
|
#sub_type ⇒ Object
32
33
34
|
# File 'lib/file_info.rb', line 32
def sub_type
@sub_type ||= type.split('/')[1]
end
|
#type ⇒ Object
21
22
23
24
25
26
|
# File 'lib/file_info.rb', line 21
def type
@type ||= begin
match = content_type.match(MIME_TYPE_REGEX)
match ? match[0] : DEFAULT_MIME_TYPE
end
end
|