Wednesday, October 14, 2009

curlgen with Ruby Rails: Mime::Type.register and response.rb

I took some time today to try to see what is happening with default MIME content_type over at lighthouseapp.com

But I am still at sea ...

In the meantime, the Rails code states that we must not use the Response class itself. So what to do if you want to change a default MIME type across a site. For example, the default in the Mailer is 'text/plain'. And in the Response class there is a method

   def assign_default_content_type_and_charset!
      self.content_type ||= Mime::HTML

which is immediately called by

  def prepare!
    assign_default_content_type_and_charset!
    handle_conditional_get!
    set_content_length!

The first thing was to track down the Mime module in action_controller where you can see that your type may be missing (mine was.)

So now I might start the effort to convert to non-HTML web content as site output with

    Mime::Type.register "text/vnd.curl", :curl

The Mime module has a class Type (yes, I know, but so it is) and that has a static
   @@html_types = Set.new [:html, :all]
Note that it is not
  @@markup_types

Of course, it might be easier just to go into the Response class and have it set its default to the Mime::Type class static default.

But should it really be necessary to repair and modify these classes to achieve something so obvious as the default MIME Content-Type for an HTTP web framework?

That's where the hope lies with Rails 3.  But Rails 3 will be a marriage with merb and there will have to be compromises. But we should be able to hope that hard-coding the MIME defaults will be a thing of the past.

Of course for individual controllers you can go piecemeal with

  class MyApplicationController < ActionController::Base



    before_filter :set_content_type
    def set_content_type
     @headers["Content-Type"] = "text/vnd.curl; charset=utf-8"
    end
  end
 
but then you are faced with tracking down just how much of ApplicationController you must override. For example,
 
  def record_not_found
    render :text => "404 Not Found", :status => 404
  end
 
must become something like
 
  def record_not_found
    render :text => myApp.msg_404, :content_type => 'text/vnd.curl' :status => 404
  end

If you are aware of how Rails on ruby 1.8.6 can globally alter the Response content_type, please add a comment.  I don't see the answer over in the Rack module where you will find hard-coded

      @header = Utils::HeaderHash.new({"Content-Type" => "text/html"}.merge(header))

Oops.

No comments: