2011-10-08 17:36:38 -04:00
|
|
|
module Utils
|
2011-10-20 15:00:00 -04:00
|
|
|
module FileHelper
|
2011-10-26 09:46:25 -04:00
|
|
|
def binary?(string)
|
2011-10-20 15:00:00 -04:00
|
|
|
string.each_byte do |x|
|
2011-10-26 09:46:25 -04:00
|
|
|
x.nonzero? or return true
|
2011-10-20 15:00:00 -04:00
|
|
|
end
|
|
|
|
false
|
|
|
|
end
|
|
|
|
|
|
|
|
def image?
|
|
|
|
mime_type =~ /image/
|
|
|
|
end
|
|
|
|
|
|
|
|
def text?
|
|
|
|
mime_type =~ /application|text/ && !binary?(data)
|
|
|
|
end
|
|
|
|
end
|
|
|
|
|
|
|
|
module Colorize
|
|
|
|
def colorize
|
2011-11-30 02:05:37 -05:00
|
|
|
system_colorize(data, name)
|
2011-10-21 08:35:42 -04:00
|
|
|
end
|
|
|
|
|
|
|
|
def system_colorize(data, file_name)
|
2012-03-13 15:07:30 -04:00
|
|
|
options = { :encoding => 'utf-8', :linenos => 'True' }
|
|
|
|
|
|
|
|
# Try detect language with pygments
|
|
|
|
Pygments.highlight data, :filename => file_name, :options => options
|
|
|
|
rescue
|
|
|
|
# if it fails use manual detection
|
2011-10-21 08:35:42 -04:00
|
|
|
ft = handle_file_type(file_name)
|
2012-03-13 15:07:30 -04:00
|
|
|
Pygments.highlight(data, :lexer => ft, :options => options)
|
2011-10-20 15:00:00 -04:00
|
|
|
end
|
|
|
|
|
2012-03-13 15:07:30 -04:00
|
|
|
def handle_file_type(file_name)
|
2011-12-05 05:21:44 -05:00
|
|
|
case file_name
|
2012-03-13 15:07:30 -04:00
|
|
|
when /(\.ru|Gemfile)$/
|
2011-10-20 15:00:00 -04:00
|
|
|
:ruby
|
|
|
|
else
|
|
|
|
:text
|
|
|
|
end
|
2011-10-08 17:36:38 -04:00
|
|
|
end
|
|
|
|
end
|
|
|
|
end
|