需要为Yesod路径定义什么类型的类? [英] What typeclasses need to be defined for a Yesod path?
问题描述
在我的应用程序中,我的数据模型有几个不同的使用Integer或String作为标识符的实例。为了安全起见,我已经将这些标识符封装到newtype声明中,如下所示:
newtype DocId = DocId Integer
newtype GroupName = GroupName String
newtype UserName = UserName String
当我设置我的Yesod路径,我发现我必须为其中的每一个创建至少三个实例,并且实例几乎总是相同的
instance Read DocId其中
readsPrec prec val = case读取val
(i,):_ - > [(DocId i,)]
[] - > []
实例B.ToMarkup DocId其中
toMarkup(DocId val)= B.toMarkup val
实例PathPiece DocId其中
toPathPiece(DocId i )= T.pack $ show i
fromPathPiece s =
case reads
(i,)的$ T.unpack s:_ - >只需
[] - > Nothing
这段文字一遍又一遍。
为了在URL中呈现我的数据类型(例如@ {ViewDocument docId})并能够解析这些URL,我真的需要设置什么?
派生PathPiece
>在每个新数据类型下,或者派生实例PathPiece DocId
,如果你不能直接派生数据类型。 对于要成为路由一部分的每种数据类型,您都需要Read,Show和PathPiece实例。
In my application, my data model has several different instances of using an Integer or a String for some identifier. For safety, I've gone ahead and wrapped those identifiers into newtype declarations like so:
newtype DocId = DocId Integer
newtype GroupName = GroupName String
newtype UserName = UserName String
When I'm setting up my Yesod paths, I'm discovering that I have to create at least three instances for each of these, and the instances are almost always identical
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
This text, over and over again.
What do I really need to set up in order to both render my data type in URLs (like @{ViewDocument docId}) and be able to parse those URLs?
If you turn on GeneralizedNewtypeDeriving
, then you can just add deriving PathPiece
under each new datatype, or deriving instance PathPiece DocId
if you can't derive directly on the datatype.
You will need Read, Show, and PathPiece instances for every datatype that is to be part of a route.
这篇关于需要为Yesod路径定义什么类型的类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!