DEV Community

Cover image for Rails Action Pack Variants
Deepak Singh
Deepak Singh

Posted on

6 3

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

AWS GenAI LIVE image

How is generative AI increasing efficiency?

Join AWS GenAI LIVE! to find out how gen AI is reshaping productivity, streamlining processes, and driving innovation.

Learn more

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.

Qodo Takeover

Introducing Qodo Gen 1.0: Transform Your Workflow with Agentic AI

Rather than just generating snippets, our agents understand your entire project context, can make decisions, use tools, and carry out tasks autonomously.

Read full post

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay