Recently on one of the projects at Eloquent Studio, I needed to render two very different view templates for desktop and mobile, even Bootstrap responsive design did not fit the requirement.
A little hesitant to roll out a custom solution for such a common requirement, I did some google searches and struck up the RailsGuides. ActionPack Variants
is just what I was looking for. ActionPack Variants
is a specialisation of request format
. Released with Rails 4.1, the api was later improved to its current state in Rails 5 as per this PR
Within the controller action's respond to block
# app/controllers/patterns_controller.rb
before_action :set_variant, only: :show
def show
format.html do |html|
html.phone
html.tablet
end
end
private
def set_variant
case request.user_agent
when /iPad/i
request.variant = :tablet
when /iPhone/i
request.variant = :phone
when /Android/i && /mobile/i
request.variant = :phone
when /Android/i
request.variant = :tablet
when /Windows Phone/i
request.variant = :phone
end
end
And setup view templates as
# app/views/patterns/show.html.erb
# Show page for desktop view
# app/views/patterns/show.html+tablet.erb
# Show page for tablet view
# app/views/patterns/show.html+phone.erb
# Show page for phone view
Not just devices, variants can be used for more varied use cases, like rendering different view templates based on user roles.
CoverImage Credits: https://unsplash.com/@bugsster
Top comments (2)
is shortcut for for
Nice explanation, thanks.