在我的应用程序中,我的数据模型有几个使用整数或字符串作为某些标识符的不同实例。为了安全起见,我将这些标识符包装到新类型声明中,如下所示:
newtype DocId = DocId Integer
newtype GroupName = GroupName String
newtype UserName = UserName String
当我设置 Yesod 路径时,我发现我必须为每个路径创建至少三个实例,并且这些实例几乎总是相同的
instance Read DocId where
readsPrec prec val = case reads val of
(i, ""):_ -> [(DocId i, "")]
[] -> []
instance B.ToMarkup DocId where
toMarkup (DocId val) = B.toMarkup val
instance PathPiece DocId where
toPathPiece (DocId i) = T.pack $ show i
fromPathPiece s =
case reads $ T.unpack s of
(i, ""):_ -> Just i
[] -> Nothing
这段文字,一遍又一遍。
为了在 URL 中呈现我的数据类型(如 @{ViewDocument docId})并能够解析这些 URL,我真正需要设置什么?
如果你打开GeneralizedNewtypeDeriving
,那么你可以添加deriving PathPiece
在每个新数据类型下,或deriving instance PathPiece DocId
如果您无法直接派生数据类型。
对于要成为路线一部分的每个数据类型,您都需要 Read、Show 和 PathPiece 实例。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)