Programming in Paradise

Wednesday, March 29, 2006

Rails 1.1 Custom Types for respond_to

Here is a simple example of adding new MIME-types and response handlers in Rails 1.1. I placed the following in $APP/lib/mime_responds.rb although it probably should be packaged up as a Plugin, and the Mime registration should probably be put somewhere else, but this will do for now...

include Mime
WML = Type.new("text/vnd.wap.wml", :wml, %w( text/vnd.wap.wml ))
LOOKUP['text/vnd.wap.wml'] = WML

module ActionController
module MimeResponds
class Responder
for mime_type in %w( wml )
eval <<-EOT
def #{mime_type}(&block)
custom(#{mime_type.upcase}, &block)
end
EOT
end
end
end
end

Add the following line to the end of the $APP/config/environment.rb file:

require_dependency 'lib/mime_responds'

Then in a controller:

respond_to do |wants|
wants.html
wants.wml { render :action => "#{action_name}.wml", :layout => 'application.wml'}
end

That should do it. You can substitute alternate content types and do other funky stuff, but this is at least a starting point.