iphoneruby-on-rails-3respond-with

(Missing) Steps to support iPhone in new Rails 3 app


What step am I missing? The view being returned to my iPhone is coming from application.html.erb and index.html.erb

Step 1: In config/initializers/mime_types.rb uncomment the declaration line for the iPhone:

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

Step 2: Make a copy of app/views/layouts/application.html.erb calling it application.iphone.erb (I like to change the title to something specific to your iPhone so you can see immediately that the correct layout is being used)

<title>My iPhone Tasks</title>

Step 3: Make copies of the necessary view files in your controllers, calling them things like index.iphone.erb

Step 4: Decide whether to stick with the Rails 2 model of respond_to blocks that specifically call out a format of iphone or switch to the more DRY approach that uses the respond_with call. That's what I've done, er tried ;-)

Step 4a: Add to your controller the respond_to block:

class TasksController < ApplicationController
respond_to :html, :iphone

Step 4b: DRY up your methods, such as:

def index
  @tasks = Task.all
  respond_with (@tasks)
end

Step 5: Restart your server and hit the app from your iPhone.


Solution

  • You have to write a responder for your mobile mime type for respond_with to properly work.

    Define the responder in application_controller.rb:

      def self.responder
        MobileResponder
      end
    
    class MobileResponder < ActionController::Responder
    
      def to_format
        super
      rescue ActionView::MissingTemplate => e
        if request.format == "iphone"
          navigation_behavior(e)
        else
          raise unless resourceful?
          api_behavior(e)
        end
      end
    end