Checking if users device is mobile

Going over the code line by line

After the request is made the first controller that’s triggered is the application_controller which has the code that you see in the gist. There are two ways check_for_mobile can check if the request is coming from a mobile device

Someone manually adds a value to params which

will set session[:mobile_override] to some truthy value. Once mobile_device? is called session[:mobile_override] will be set equal to 1 which can then be used at any given point in time of the users session. If params[:mobile] wasn’t set manually then session[:mobile_override] will return nil in the mobile_device? method and request.env[“HTTP_USER_AGENT”] is run against a regex to see if

the device the request is coming from is mobile, you can configure the regex depending on what devices you want to target. “HTTP_USER_AGENT” return a string e.g “Mozilla/5.0 (iPhone; CPU iPhone OS 7_0 like Mac OS X; en-us) AppleWebKit/537.51.1 (KHTML, like Gecko) Version/7.0 Mobile/11A465 Safari/9537.53," in this particular case the agent was a chrome emulation of an iPhone 5.

In both cases prepare_for_mobile is subsequently called which uses a Rails method prepend_view_path. This is an important step because here you’re specifying a separate views folder, I suggest creating a second views folder called views_mobile, where the controller actions will be called.

Choose the controller where you want to check if the user device is mobile for a particular action (or all actions) by adding a before_filter and call the method check_for_mobile that we created in our application_controller. Line 13 in the gist renders a completley seperate layout (we’re going to call is “application_mobile”) for mobile devices. All we have to do now is create a few files in our Rails app require foundation and voila!