@@ -2,6 +2,8 @@
22module Web.PathPieces
33 ( PathPiece (..)
44 , PathMultiPiece (..)
5+ , readFromPathPiece
6+ , showToPathPiece
57 -- * Deprecated
68 , toSinglePiece
79 , toMultiPiece
@@ -16,6 +18,7 @@ import qualified Data.Text.Lazy as L
1618import qualified Data.Text.Read
1719import Data.Time (Day)
1820import Control.Exception (assert)
21+import Text.Read (readMaybe)
1922
2023class PathPiece s where
2124 fromPathPiece :: S.Text -> Maybe s
@@ -122,6 +125,24 @@ instance PathPiece a => PathMultiPiece [a] where
122125 fromPathMultiPiece = mapM fromPathPiece
123126 toPathMultiPiece = map toPathPiece
124127
128+-- | A function for helping generate free 'PathPiece'
129+-- instances for enumeration data types
130+-- that have derive 'Read' and 'Show'.
131+-- Intended to be used like this:
132+--
133+-- > data MyData = Foo | Bar | Baz
134+-- > deriving (Read,Show)
135+-- > instance PathPiece MyData where
136+-- > fromPathPiece = readFromPathPiece
137+-- > toPathPiece = showToPathPiece
138+--
139+readFromPathPiece :: Read s => S.Text -> Maybe s
140+readFromPathPiece = readMaybe . S.unpack
141+
142+-- | See the documentation for 'readFromPathPiece'.
143+showToPathPiece :: Show s => s -> S.Text
144+showToPathPiece = S.pack . show
145+
125146{-# DEPRECATED toSinglePiece "Use toPathPiece instead of toSinglePiece" #-}
126147toSinglePiece :: PathPiece p => p -> S.Text
127148toSinglePiece = toPathPiece