Adjustable Mime Type Plugin

One day I got sick and tired of constantly repeating myself while implementing various mime-type aliases like iPhone and iPad views so I made this possible:

Mime::Type.register_alias "text/html", :iphone do |req|
  req.user_agent =~ /Mobile.*Safari/
end

Mime::Type.register_alias "text/html", :ipad do |req|
  req.user_agent =~ /iPad/
end

The old way of dealing with this looks something like:

Mime::Type.register_alias "text/html", :iphone

Then adding a bunch of before_filters in the application controller like:

before_filter :set_iphone_format

def set_iphone_format
  if get_head_method?
    if is_iphone_request? || is_iphone_format? || is_iphone_subdomain?
      request.format = cookies["browser"] == "desktop" ? :html : :iphone
    end
  end
end

def is_iphone_format?
  request.format.to_sym == :iphone
end

def is_iphone_request?
  request.user_agent =~ /Mobile.*Safari/
end

This plugin makes dealing with mime-type formats much more concise and moves the logic of dealing with those adjustments to one place.

__This has not been tested with Rails 3!__

Note on Patches/Pull Requests

  • Fork the project.

  • Make your feature addition or bug fix.

  • Add tests for it. This is important so I don’t break it in a future version unintentionally.

  • Commit, do not mess with rakefile, version, or history. (if you want to have your own version, that is fine but bump version in a commit by itself I can ignore when I pull)

  • Send me a pull request. Bonus points for topic branches.

Copyright © 2010 Brad Gessler. See LICENSE for details.