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.

2 Comments:

  • rick - Mime::Type.register :wml, 'text/vnd.wap.wml'

    Someone already thought of that :)

    By Anonymous Anonymous, at 4:25 PM  

  • Just wanted to comment that Mime::Type.register should take those arguments in reverse order.

    By Anonymous Anonymous, at 10:07 PM  

Post a Comment

Links to this post:

Create a Link

<< Home