Nakilon
Nakilon

Reputation: 35092

Detect browser in Sinatra

I need to know (on .rb/.haml level) if device is mobile or if browser is not supported. I don't want (or it won't work well for my need) to parse userAgent on client side.

Upvotes: 2

Views: 698

Answers (2)

Luisa Fernanda
Luisa Fernanda

Reputation: 21

Also you can use:

require 'sinatra'

get '/' do

 request.user_agent

end

Upvotes: 2

Nakilon
Nakilon

Reputation: 35092

Gem browser seems to be what I exactly need. It is mainly used in Rails and I could not find the fully correct snippet for Sinatra, so I share my solution:

require "browser"

...

get "/"
  browser = Browser.new request.user_agent, accept_language: request.env["HTTP_ACCEPT_LANGUAGE"]
  break haml(:mobile, locals: { reason: "you are mobile" }) if browser.device.mobile?
  break haml(:mobile, locals: { reason: "you are not chrome" }) if not browser.chrome?
  ...
  haml :index
end

Upvotes: 4

Related Questions