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'
- VERSION =
'0.5.0'
Instance Attribute Summary collapse
Class Method Summary
collapse
Instance Method Summary
collapse
Constructor Details
#initialize(output) ⇒ FileInfo
Returns a new instance of FileInfo.
16
17
18
|
# File 'lib/file_info.rb', line 16
def initialize(output)
@content_type = output.strip
end
|
Instance Attribute Details
#content_type ⇒ Object
Returns the value of attribute content_type.
14
15
16
|
# File 'lib/file_info.rb', line 14
def content_type
@content_type
end
|
Class Method Details
.load(filename) ⇒ Object
51
52
53
54
|
# File 'lib/file_info.rb', line 51
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
56
57
58
59
60
61
62
63
64
|
# File 'lib/file_info.rb', line 56
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
41
42
43
|
# File 'lib/file_info.rb', line 41
def charset
@charset ||= (matches = content_type.match(CHARSET_REGEX)) ? matches[1] : 'binary'
end
|
#encoding ⇒ Object
45
46
47
48
49
|
# File 'lib/file_info.rb', line 45
def encoding
@encoding ||= ::Encoding.find(charset)
rescue ArgumentError => e
raise UnknownEncodingError, e.message
end
|
24
25
26
|
# File 'lib/file_info.rb', line 24
def media_type
@media_type ||= type.split('/')[0]
end
|
#mime_type ⇒ Object
32
33
34
35
36
37
38
39
|
# File 'lib/file_info.rb', line 32
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
28
29
30
|
# File 'lib/file_info.rb', line 28
def sub_type
@sub_type ||= type.split('/')[1]
end
|
#type ⇒ Object
20
21
22
|
# File 'lib/file_info.rb', line 20
def type
@type ||= content_type.match(MIME_TYPE_REGEX)[0]
end
|