on master help sign in
A bit classier
ac9f8c7Michael Snoyman
Data/Yaml/Builder.hs+4−4
@@ -60,11 +60,11 @@ toEvents :: YamlBuilder -> [Event]
60toEvents (YamlBuilder front) =
60toEvents (YamlBuilder front) =
61 EventStreamStart : EventDocumentStart : front [EventDocumentEnd, EventStreamEnd]
61 EventStreamStart : EventDocumentStart : front [EventDocumentEnd, EventStreamEnd]
62
62
63−toSource :: Monad m => YamlBuilder -> Source m Event
63+toSource :: (Monad m, ToYaml a) => a -> Source m Event
64−toSource = mapM_ yield . toEvents
64+toSource = mapM_ yield . toEvents . toYaml
65
65
66−toByteString :: YamlBuilder -> ByteString
66+toByteString :: ToYaml a => a -> ByteString
67toByteString yb = unsafePerformIO $ runResourceT $ toSource yb $$ encode
67toByteString yb = unsafePerformIO $ runResourceT $ toSource yb $$ encode
68
68
69−writeYamlFile :: FilePath -> YamlBuilder -> IO ()
69+writeYamlFile :: ToYaml a => FilePath -> a -> IO ()
70writeYamlFile fp yb = runResourceT $ toSource yb $$ encodeFile fp
70writeYamlFile fp yb = runResourceT $ toSource yb $$ encodeFile fp
builder-test.hs+13−16
@@ -3,22 +3,19 @@ import Data.Yaml.Builder
3import qualified Data.ByteString as S
3import qualified Data.ByteString as S
4import Data.Text (Text)
4import Data.Text (Text)
5
5
6−asText :: Text -> Text
6+data Person = Person
7−asText = id
7+ { name :: !Text
8−
8+ , age :: !Int
9−asInt :: Int -> Int
9+ }
10−asInt = id
10+instance ToYaml Person where
11+ toYaml (Person n a) = mapping
12+ [ "name" .= n
13+ , "age" .= a
14+ ]
11
15
12main :: IO ()
16main :: IO ()
13main = do
17main = do
14− let yb = array
15− [ mapping
16− [ "name" .= asText "Alice"
17− , "age" .= asInt 57
18− ]
19− , mapping
20− [ "name" .= asText "Bob"
21− , "age" .= asInt 23
22− ]
23− ]
24− S.putStr $ toByteString yb
18+ S.putStr $ toByteString
19+ [ Person "Alice" 57
20+ , Person "Bob" 23
21+ ]