Module: Wcl::Convert

Defined in:
lib/wcl/convert.rb

Overview

JSON-to-Ruby value conversion for WCL WASM binding.

Class Method Summary collapse

Class Method Details

.json_to_block_ref(obj) ⇒ Object



59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
# File 'lib/wcl/convert.rb', line 59

def json_to_block_ref(obj)
  attrs = (obj["attributes"] || {}).transform_values { |v| json_to_ruby(v) }
  children = (obj["children"] || []).map { |c| json_to_block_ref(c) }
  decorators = (obj["decorators"] || []).map do |d|
    Decorator.new(
      name: d["name"],
      args: (d["args"] || {}).transform_values { |v| json_to_ruby(v) }
    )
  end

  BlockRef.new(
    kind: obj["kind"],
    id: obj["id"],
    attributes: attrs,
    children: children,
    decorators: decorators
  )
end

.json_to_blocks(json_str) ⇒ Object



43
44
45
46
# File 'lib/wcl/convert.rb', line 43

def json_to_blocks(json_str)
  data = JSON.parse(json_str)
  data.map { |b| json_to_block_ref(b) }
end

.json_to_diagnostics(json_str) ⇒ Object



48
49
50
51
52
53
54
55
56
57
# File 'lib/wcl/convert.rb', line 48

def json_to_diagnostics(json_str)
  data = JSON.parse(json_str)
  data.map do |d|
    Diagnostic.new(
      severity: d["severity"],
      message: d["message"],
      code: d["code"]
    )
  end
end

.json_to_ruby(val) ⇒ Object



8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
# File 'lib/wcl/convert.rb', line 8

def json_to_ruby(val)
  case val
  when nil, true, false, String
    val
  when Integer
    val
  when Float
    val == val.to_i && !val.is_a?(Float) ? val.to_i : val
  when Array
    val.map { |v| json_to_ruby(v) }
  when Hash
    # Check for set encoding
    if val["__type"] == "set" && val.key?("items")
      items = val["items"].map { |v| json_to_ruby(v) }
      begin
        Set.new(items)
      rescue
        items
      end
    # Check for block ref encoding
    elsif val.key?("kind") && (val.key?("attributes") || val.key?("children") || val.key?("decorators"))
      json_to_block_ref(val)
    else
      val.transform_values { |v| json_to_ruby(v) }
    end
  else
    val
  end
end

.json_to_values(json_str) ⇒ Object



38
39
40
41
# File 'lib/wcl/convert.rb', line 38

def json_to_values(json_str)
  data = JSON.parse(json_str)
  data.transform_values { |v| json_to_ruby(v) }
end