DEV Community

Cover image for Rails Action Pack Variants
Deepak Singh
Deepak Singh

Posted on

Rails Action Pack Variants

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
Enter fullscreen mode Exit fullscreen mode

And setup view templates as

# app/views/patterns/show.html.erb

# Show page for desktop view
Enter fullscreen mode Exit fullscreen mode
# app/views/patterns/show.html+tablet.erb

# Show page for tablet view
Enter fullscreen mode Exit fullscreen mode
# app/views/patterns/show.html+phone.erb

# Show page for phone view
Enter fullscreen mode Exit fullscreen mode

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)

Collapse
 
amit_savani profile image
Amit Patel
render variants: [:phone, :tablet]
Enter fullscreen mode Exit fullscreen mode

is shortcut for for

format.html do |html|
    html.phone
    html.tablet
  end
Enter fullscreen mode Exit fullscreen mode
Collapse
 
hasantezcan profile image
Hasan TEZCAN

Nice explanation, thanks.