Python vs Ruby – The Workshape Smackdown

Python vs Ruby – The Workshape Smackdown

Advertisements

How to make different layouts for device with Rails?

Rails version: >= 4.1


Application Controller

app/controllers/application_controller.rb

def layout_by_device
  case request.user_agent
  when /iPad/
    request.variant = :tablet
  when /iPhone|Mobile/
    request.variant = :mobile
  else
    request.variant = :pc
  end
end

Other Controller

app/controllers/products_controller.rb

before_action :layout_by_device

def index
  @products = Product.all
  respond_to do |format|
    format.html do |html|
      html.pc { render layout: 'pc' }
      html.mobile { render layout: 'mobile' }
      html.tablet { render layout: 'tablet' }
    end
  end
end

View

  • app/views/layouts/pc.html.erb
  • app/views/layouts/mobile.html.erb
  • app/views/layouts/tablet.html.erb
  • app/views/products/index.html.erb
  • app/views/products/index.html+mobile.erb
  • app/views/products/index.html+tablet.erb

http://guides.rubyonrails.org/4_1_release_notes.html#action-pack-variants