Class: Pangrid::Json

Inherits:
Plugin show all
Defined in:
lib/pangrid/plugins/json.rb

Constant Summary collapse

DESCRIPTION =
"Simple JSON format"

Constants inherited from Plugin

Plugin::FAILED, Plugin::MISSING_DEPS, Plugin::REGISTRY

Instance Method Summary collapse

Methods inherited from Plugin

class_to_name, get, inherited, list_all, load_all, load_plugin

Methods included from PluginUtils

#check

Instance Method Details

#read(data) ⇒ Object



47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
# File 'lib/pangrid/plugins/json.rb', line 47

def read(data)
  json = ::JSON.parse(data)
  xw = XWord.new

  xw.height = json['rows']
  xw.width = json['cols']
  xw.solution = Array.new(xw.height) { Array.new(xw.width) }
  json['cells'].each do |c|
    cell = Cell.new
    s = c['contents']
    cell.solution =
      case s
      when ""; :null
      when "#"; :black
      else
        if s.length == 1
          s
        else
          Rebus.new s
        end
      end
    x, y = c['x'], c['y']
    xw.solution[y][x] = cell
  end
  xw.across_clues = json['across']
  xw.down_clues = json['down']
  xw
end

#write(xw) ⇒ Object



20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
# File 'lib/pangrid/plugins/json.rb', line 20

def write(xw)
  cells = []
  (0 ... xw.height).each do |y|
    (0 ... xw.width).each do |x|
      cell = xw.solution[y][x]
      s = case cell.solution
          when :black; '#'
          when :null; ''
          when Rebus; cell.solution.inspect
          else; cell.solution
          end

      cells.push({ x: x, y: y, contents: s })
    end
  end

  h = {
    rows: xw.height,
    cols: xw.width,
    cells: cells,
    across: xw.across_clues,
    down: xw.down_clues
  }

  ::JSON.generate(h)
end