- Published
- Author
- Syed SibtainSystem Analyst
In a Rails application, we can provide different views and behaviours based on the type of device accessing our application. One of the ways to achieve this is by using the
1. First, determine if the request is coming from a mobile device and set variant in the controller.
2. Now, create mobile-specific views. For example, if we have an
With the variant set, Rails will automatically choose the correct view.
#rubyonrails
set_variant method along with mobile-specific templates like index.html+mobile1. First, determine if the request is coming from a mobile device and set variant in the controller.
Ruby
def set_variant
browser = Browser.new(request.user_agent)
if browser.device.mobile?
request.variant = :mobile
else
request.variant = :desktop
end
end2. Now, create mobile-specific views. For example, if we have an
index.html.erb view, we can create a mobile-specific version by adding +mobile to the filename.Code
app/views/orders/index.html.erb
app/views/orders/index.html+mobile.erbWith the variant set, Rails will automatically choose the correct view.
#rubyonrails