LoginSignup
2
3

More than 5 years have passed since last update.

Rails UserAgentの設定の仕方 PCとSmartPhoneの表示するViewを切り替える

Posted at

PCとSmartPhoneの表示するViewを切り替えるための設定をします。
便利なgemがあるのでそちらを活用します。

k0kubun/rack-user_agent

まずはgemのinstall

Gemfile
gem 'rack-user_agent'

これでbundle install。

以下のような感じにapplicationコントローラー内で設定します。

/app/controller/application_controller.rb
class ApplicationController < ActionController::Base
  before_action :set_request_variant

  private

  def set_request_variant
    if from_smartphone?
      request.variant = :smartphone
    end
  end

  def from_smartphone?
    request.from_android? || request.from_iphone? || request.from_ipod? || request.from_windows_phone? 
  end
end

あとは、index.html.hamlindex.html+smartphone.haml を作成すればデバイスによって使用するViewのファイルを切り分けてくれます。
PCで開くと通常のViewファイルが表示され、smartphoneで開くとsmartphoneがついたファイルが表示されます。

2
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
3