Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Returning mobile views from rails, either by using a custom view path ("views_mobile") or by setting a custom request format.
class ApplicationController < ActionController::Base
before_filter :prepend_view_path_if_mobile
def mobile_request?
@mobile_request ||= (request.subdomains.first == domain_prefixes[:mobile])
end
helper_method :mobile_request?
def prepend_view_path_if_mobile
prepend_view_path Rails.root + 'app' + 'views_mobile' if mobile_request?
end
# use this as a before_filter if you want to load a custom template using the [action].mobile.erb naming convention
# by default we use the prepend_view_path to load the files from the views_mobile path instead or using the format parameter
def prepare_for_mobile
request.format = :mobile if mobile_request?
end
end
# config/initializers/mime_types.rb
# Add new mime types for use in respond_to blocks:
# Mime::Type.register "text/richtext", :rtf
Mime::Type.register_alias "text/html", :mobile
class SampleController < ApplicationController
before_filter :prepare_for_mobile, only: [:index]
def index
@samples = Sample.all
# if this is an ajax request (X-Requested-With: XMLHttpRequest)
# note this is true for jQuery mobile page views as well
if request.xhr?
respond_to do |format|
end
else
# if you can rely on defaults, you can use
# respond_to :html, :js
respond_to do |format|
# if this is a mobile request, it will use index.mobile.erb or fallback on index.html.erb
format.html
# custom request.format set up in application_controller if its a mobile request
format.mobile # { render partial: 'index', formats: [:html] }
format.js # defaults to index.js.erb, used when http accept header is text/javascript, application/javascript, application/x-javascript
format.json { render json: @samples }
format.any(:atom, :rss) { @samples.Sample.all }
format.all { render text: "All other mime types will fall through to this..." }
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment