Skip to content

Instantly share code, notes, and snippets.

@alg alg/Main.elm
Created Dec 2, 2016

What would you like to do?
decodeModel : Json.Decode.Value -> Result String Model
decodeModel modelJson =
Json.Decode.decodeValue modelDecoder modelJson
modelDecoder : Json.Decode.Decoder Model
modelDecoder =
Json.Decode.map4 Model
(field "todos" (Json.Decode.list todoDecoder))
(field "todo" todoDecoder)
(field "filter" filterStateDecoder)
(field "nextIdentifier" int)
todoDecoder : Json.Decode.Decoder Todo
todoDecoder =
Json.Decode.map4 Todo
(field "title" Json.Decode.string)
(field "completed" Json.Decode.bool)
(field "editing" Json.Decode.bool)
(field "identifier"
filterStateDecoder : Json.Decode.Decoder FilterState
filterStateDecoder =
decodeFilterState string =
case string of
"All" -> Result.Ok All
"Active" -> Result.Ok Active
"Completed" -> Result.Ok Completed
_ -> Result.Err ("Not a valid filterState: " ++ string)
customDecoder Json.Decode.string decodeFilterState
customDecoder decoder toResult =
(\a ->
case toResult a of
Ok b -> Json.Decode.succeed b
Err err -> err

This comment has been minimized.

Copy link

gabrielelana commented Dec 29, 2016

You can rewrite the last part with

filterStrategyDecoder : Decode.Decoder FilterStrategy
filterStrategyDecoder =
        decodeWith : String -> Decode.Decoder FilterStrategy
        decodeWith s =
            case s of
                "All" ->
                    Decode.succeed All

                "Active" ->
                    Decode.succeed Active

                "Completed" ->
                    Decode.succeed Completed

                _ ->
           (s ++ " is not a valid FilterStrategy")
        Decode.string |> Decode.andThen decodeWith
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.