我正在尝试为我的控制器编写一个辅助方法,以确定设备是否可移动,以便我可以加载适当的模板。这是我到目前为止所得到的:
def isMobile[A](implicit request: Request[A]): Boolean = {
request.headers.get("User-Agent").exists(agent =>
if (agent.matches("/(iPhone|webOS|iPod|Android|BlackBerry|mobile|SAMSUNG|IEMobile|OperaMobi)/"))
true
else false)
}
这将不起作用,因为用户代理不仅向我们提供了设备,还为我们提供了字符串包含很多不错的东西,例如:
Mozilla/5.0 (iPhone; CPU iPhone OS 6_0 like Mac OS X) AppleWebKit/536.26 (KHTML, like Gecko) Version/6.0 Mobile/10A403 Safari/8536.25
解析此信息的正确方法是什么?是否应该使用用户代理创建字典,然后查看当前字符串是否包含其中之一?创建一个匹配不同用户代理的主要的正则表达式?也许有一些我没有找到的Scala库可以做到这一点?
谢谢!
当然,如Sniffer所建议的,执行此操作的一种方法是像unanchored
进行部分匹配,如下所示:
val Pattern = "(iPhone|webOS|iPod|Android|BlackBerry|mobile|SAMSUNG|IEMobile|OperaMobi)".r.unanchored
def isMobile[A](implicit request: Request[A]): Boolean = {
request.headers.get("User-Agent").exists(agent => {
agent match {
case Pattern(a) => true
case _ => false
}
})
}
也许还有其他更好的方法?
使用jakob的答案中的模式,也许将函数重写为:
def isMobile[A](implicit request: Request[A]): Boolean =
request.headers.get("User-Agent") match {
case Some(Pattern(a)) => true
case _ => false
}
如果您更喜欢使用字符串:
def isMobile(ua: String) =
ua match {
case uaMobilePattern(a) => true
case _ => false
}
您可以使用https://github.com/ua-parser/uap-scala
它基于https://github.com/ua-parser/uap-core,其中包含许多语言用于库的数据。它的核心是https://github.com/ua-parser/uap-core/blob/master/regexes.yaml,看起来很全面。