Skip to content

Instantly share code, notes, and snippets.

@opsb
Last active August 10, 2016 12:25
Show Gist options
  • Select an option

  • Save opsb/f783a828bd4c5f3f8fafa4f862bb130a to your computer and use it in GitHub Desktop.

Select an option

Save opsb/f783a828bd4c5f3f8fafa4f862bb130a to your computer and use it in GitHub Desktop.
Elm decoding polymorphic json list
[
{
"type": "summary",
"description": "an awesome summary",
"title": "an awesome title"
},
{
"type": "video",
"mpg": "http://vids.com/awesome.mpg"
}
]
module Models.Attachment exposing (Attachment (..), )
import Json.Decode as JD exposing ((:=))
type alias VideoRecord =
{ mpg : String
}
type alias SummaryRecord =
{ title : String
, description : String
}
type Attachment
= Video VideoRecord
| Summary SummaryRecord
videoDecoder =
JD.object1 VideoRecord
("mpg" := JD.string)
|> JD.map Video
summaryDecoder =
JD.object2 SummaryRecord
("title" := JD.string)
("description" := JD.string)
|> JD.map Summary
decoder =
JD.oneOf ([ videoDecoder, summaryDecoder ])
listDecoder =
JD.list decoder
module Models.AttachmentTest exposing (..)
import Test exposing (..)
import Expect
import Json.Decode exposing (decodeString)
import Models.Attachment as Attachment
import Models.Attachment exposing (..)
videoJson =
"""
{
"type": "video",
"mpg": "http://vids.com/awesome.mpg"
}
"""
summaryJson =
"""
{
"type": "summary",
"description": "an awesome summary",
"title": "an awesome title"
}
"""
attachmentsJson =
"""
[
{
"type": "summary",
"description": "an awesome summary",
"title": "an awesome title"
},
{
"type": "video",
"mpg": "http://vids.com/awesome.mpg"
}
]
"""
all : Test
all =
describe "Attachment"
[ test "decode video" <|
\() ->
Expect.equal
(decodeString Attachment.decoder videoJson)
(Ok
(Video { mpg = "http://vids.com/awesome.mpg" })
)
, test "decode summary" <|
\() ->
Expect.equal
(decodeString Attachment.decoder summaryJson)
(Ok
(Summary { description = "an awesome summary", title = "an awesome title" })
)
, test "decode list containing a summary and video" <|
\() ->
Expect.equal
(decodeString Attachment.listDecoder attachmentsJson)
(Ok
[ Summary { description = "an awesome summary", title = "an awesome title" }
, Video { mpg = "http://vids.com/awesome.mpg" }
]
)
]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment