【问题标题】:Yesod route containing a `Maybe a` argumentYesod 路由包含一个“可能是一个”参数
【发布时间】:2014-06-22 15:25:58
【问题描述】:

我一直在尝试在路线中使用Maybe a。到目前为止我试过了

/u/#Maybe UserId
/u/#(Maybe UserId)
/u/#Maybe-UserId

/u/#MaybeUserId

在哪里

type MaybeUserId = Maybe UserId

但没有多大成功。

奇怪的是,#Maybe-UserId 与使用 Maybe UserId 的处理程序编译得很好,但是,即使使用下面的新 PathPiece 实例,它也无法找到匹配项。

instance (PathPiece a) => PathPiece (Maybe a) where
    fromPathPiece s = case s of
        "Nothing" -> Nothing
        _ -> Just $ fromPathPiece s
    toPathPiece m = case m of
        Just s -> toPathPiece s
        _ -> "Nothing"

创建Maybe 路由并且不必为我想使用的每个Maybe a 声明一个类型和实例,我缺少什么?

编辑:由于某种原因,当使用Ǹothing 以外的任何东西时,实例工作正常。

edit2: "Nothing" -> Nothing 实际上表示 PathPiece 解析失败,这不是预期的结果。 "Nothing" -> Just Nothing 做正确的事。

【问题讨论】:

    标签: haskell routes yesod maybe


    【解决方案1】:

    带有空参数(以斜杠结尾)的路由将恢复为以前一个路径片段结尾的路由,因此“/u/”永远不会匹配“/u/#MaybeUserId”

    所以在你的可选 UserId 命题中有两条不同的路线:

    /u  UserNoIdR  GET
    
    /u/#UserId  UserWithIdR GET
    

    更新

    如果您愿意,您可以通过一个共同的处理程序同时为它们提供服务:

    getUserNoIdR = getUserMaybe Nothing
    
    getUserWithIdR userId = getUserMaybe (Just userId)
    

    【讨论】:

    • 它需要更多的代码来完成并最终需要维护。检查我发现我的错误的问题。
    • 具有空参数(以斜杠结尾)的路由将恢复为以前一个路径片段结尾的路由。所以这里有两条不同的路线。
    【解决方案2】:

    对于所有来自 Google 的人来说,以下确实是正确的路由语法:

    /user/#Maybe-UserId    UserR GET
    

    对于处理程序:

    getUserR :: Maybe UserId -> Handler Html
    

    您可以通过 URL 访问它们

    /user/Nothing  -> Nothing
    /user/Just%207 -> Just 7
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-10-12
      • 2023-04-08
      • 2015-09-10
      • 2013-10-14
      • 2013-05-24
      • 2018-04-13
      • 2016-11-08
      相关资源
      最近更新 更多