Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does Elm have a debugging function that can print an object to the console?

Tags:

elm

I would like to be able to examine a runtime javascript object. Can I print an object to the console instead of a string?

like image 935
jz87 Avatar asked Aug 03 '16 01:08

jz87


3 Answers

You can use Debug.log, for example:

import Html exposing (text)

f x = x * x

main =
  let
    dummy = Debug.log "dump tuple" (33, 55, f)
  in text "Hello, World!"
like image 148
Tosh Avatar answered Oct 19 '22 22:10

Tosh


Unfortunately, no. All objects are converted to strings before they are sent to the console when you use Debug.log.

You can however create a function that would output the actual object using the Native layer however, this is an undocumented API and it is advisable to use it only as a last resort.

like image 8
pdamoc Avatar answered Oct 20 '22 00:10

pdamoc


I needed richer logging while working on an encoder, so I ended up writing a port for it. Here's an working example on Ellie and here's the code:

Main.elm

port module Main exposing (main)

import Browser
import Html exposing (Html, button, div, text)
import Html.Events exposing (onClick)
import Json.Encode as E exposing (Value, int, object, string)


type alias Model =
    { count : Int
    , name : String
    }


initialModel : Model
initialModel =
    { count = 0
    , name = "Foo"
    }


encodeModel : Model -> Value
encodeModel model =
    object
        [ ( "count", int model.count )
        , ( "name", string model.name )
        ]


port jsonConsole : Value -> Cmd msg


type Msg
    = ConsoleLogJson


update : Msg -> Model -> ( Model, Cmd Msg )
update msg model =
    case msg of
        ConsoleLogJson ->
            let
                json =
                    encodeModel model
            in
            ( model, jsonConsole json )


view : Model -> Html Msg
view model =
    div [] [ button [ onClick ConsoleLogJson ] [ text "Log to console" ] ]


subscriptions : Model -> Sub Msg
subscriptions _ =
  Sub.batch []


init : () -> ( Model, Cmd msg )
init flags =
    ( initialModel, Cmd.none )


main : Program () Model Msg
main =
    Browser.element
        { init = init
        , subscriptions = subscriptions
        , view = view
        , update = update
        }

index.html

<html>
<head>
  <style>
    /* you can style your program here */
  </style>
</head>
<body>
  <main></main>
  <script>
    var app = Elm.Main.init({ node: document.querySelector('main') })
    app.ports.jsonConsole.subscribe(function(json) {
      console.log(json)
    })
  </script>
</body>
</html>

I'm sure there are improvements that could be made, and I'd love to hear them!

like image 7
jc00ke Avatar answered Oct 19 '22 23:10

jc00ke