Hank Stoever
part time nerd, part time gnar.

Using Mobile Templates in a Rails app (like Github)

posted about 9 years ago - 1 min read

Github recently released mobile layouts for many pages on their website. Instead of using css media queries to change the display of the page, Github's servers respond with entirely different markup. The main advantage of this is to reduce page sizes:

github page sizes

This approach is extremely easy to replicate with Ruby on Rails. In an existing project, add mobylette to your Gemfile.

gem 'mobylette'

Then add include Mobylette::RespondToMobileRequests to application_controller.rb.

Create a new file at app/views/layouts/application.mobile.erb with the same contents as application.html.erb. Add a mobile class to your body tag, which will allow you to easily use mobile-specific css without media queries. If you want to follow Github's approach of using a smaller page size, you can do things like reduce the contents of your navigation bar. To make sure this is working, add <h1>Hello mobile user!</h1> to the top of application.mobile.erb.

Run bundle, restart your server, and open your website with something like iOS Simulator, or use localtunnel to open the website on your phone or tablet. If you see the message Hello mobile user!, everything is working. If not, you may have run into the same problems I did when using Mobylette with Rails 4 and Ruby 2.0.0. Change your Gemfile to point Mobylette to my fork:

gem 'mobylette', github: 'hstove/mobylette'

Run bundle, restart, and things should be working. You can now start to create mobile-specific templates for different pages of your website. For example, if you have a model called repositories, you could create a mobile-specific page at app/views/repositories/show.mobile.erb. Using mobile templates works the same with all view engines, so you can use show.mobile.haml.

Using mobile-specific templates is a great way to make your site load faster on phones, who often are visiting your site from a slow connection. Eliminating unneeded javascript is a quick way to cut down on a large amount of your page size. Github also uses the approach of truncating the actual content of the page they are showing, so if you want to view more, you click View More and an ajax call is made to fetch the rest of the contents of the page.

github view more

I hope you start using this in your own websites to improve accessibility from mobile devices. If you end up applying these techniques, send me your website and I'll add it to this post.

comments powered by Disqus