I have came across many projects where checking file uploads and content-type (mime-type) is poorly implemented or heavy in resource.
Methods I have seen so far:
1. Checking content-type from file name: this inefficient, a user can just rename a file and you are fooled, or the file can have a different file format and you will not get the expected result.
2. Using Rmagick to check if the file is an image. This is so slow and uses so much Ram. You can try to initialize an rmagick object from an image file, then rescue when the file is not an image.
3. Using mini_magick to check if a file. This method is faster than rmagick. Implemen ted same way as rmagick.
A Better method for OSX and Linux, is to use the command line tool “file” included in most UNIX operating systems.
It is very fast and very accurate.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | file = "/path/to/file.ext" if RUBY_PLATFORM.match(/darwin|linux|unix|solaris|bsd/) content_type = `file --raw --brief "#{file}"`.chomp case when content_type.match(/image|png|jpg|jpeg|gif/) real_type = "image" when content_type.match(/pdf/) real_type = "pdf" when content_type.match("Microsoft Word|Microsoft Office Document") real_type = "doc" else # This can go on and on real_type = "Unknown" end end |
Some examples of content types:
.doc = Microsoft Word document data
.doc = Microsoft Office Document
.pdf = PDF document, version 1.4
.pdf = PDF document, version 1.3
.psd = Adobe Photoshop Image
.png = PNG image data, 3508 x 4961, 8-bit/color RGBA, non-interlaced
.gif = GIF image data, version 89a, 195 x 109
.jpg = JPEG image data, EXIF standard
etc…
I hope this can be useful to someone.
Suppose you have a Model called Article that contains a text field and a format field.
You would like to use haml, textile or HTML to edit your Article from the admin interface.
create_table "articles", :force => true do |t| t.string "title" t.text "body" t.string "formatting_type", :limit => 20, :default => "HTML" end
app/models/article.rb
It’s quite simple. All you have to do is to add this helper in your application_helper.rb
def print_formated(type,text) case type when "HTML" text when "Plain Text" h text when "HAML" Haml::Engine.new(text).render when "Syntaxy" Syntaxi.line_number_method = 'none' Syntaxi.new(text).process when "Textile" RedCloth.new(text).to_html end end
In your views/articles/_form.haml add the select field.
= label :article, :formatting_type = select(:article, :formatting_type, Article::FORMATTING_TYPES.collect {|p| p }, { :include_blank => false })
Then in the Show view (articles/show.haml)
.article .title %h1 = h @article.title .body = print_formated(@article.formatting_type, @article.body)
that’s pretty much it.
Tommy has just released an new mysql-ruby package.
Actually 2 of them:
mysql-ruby-2.7.5 and mysql-ruby-2.8pre2
They are Ruby 1.9 compatible
Requirements
* MySQL 5.0.51a
* Ruby 1.8.6, 1.9.0
here is the link http://tmtm.org/en/mysql/ruby/
Great Job
