Class: Vega::Spec

Inherits:
Object
  • Object
show all
Defined in:
lib/vega/spec.rb

Instance Method Summary collapse

Constructor Details

#initialize(spec) ⇒ Spec

Returns a new instance of Spec.

Raises:

  • (ArgumentError)


3
4
5
6
7
# File 'lib/vega/spec.rb', line 3

def initialize(spec)
  spec = spec.spec if spec.respond_to?(:spec)
  raise ArgumentError, "Expected Hash, not #{spec.class.name}" unless spec.is_a?(Hash)
  @spec = spec.transform_keys!(&:to_s)
end

Instance Method Details

#to_html(nonce: nil) ⇒ Object Also known as: to_s



9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
# File 'lib/vega/spec.rb', line 9

def to_html(nonce: nil)
  html, js = generate_output
  nonce_html = nonce ? " nonce=\"#{ERB::Util.html_escape(nonce)}\"" : nil
  output = <<~EOS
    #{html}
    <script#{nonce_html}>
      (function() {
        var createChart = function() { #{js} };
        if ("vegaEmbed" in window) {
          createChart();
        } else {
          window.addEventListener("vega:load", createChart, true);
        }
      })();
    </script>
  EOS
  output.respond_to?(:html_safe) ? output.html_safe : output
end

#to_irubyObject

TODO only load vega-lite if $schema requires it



30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
# File 'lib/vega/spec.rb', line 30

def to_iruby
  html, js = generate_output
  output = <<~EOS
    #{html}
    <script>
      require.config({
        paths: {
          'vega': 'https://cdn.jsdelivr.net/npm/[email protected]/build/vega.min',
          'vega-util': 'https://cdn.jsdelivr.net/npm/[email protected]/build/vega-util.min',
          'vega-lite': 'https://cdn.jsdelivr.net/npm/[email protected]/build/vega-lite.min',
          'vega-embed': 'https://cdn.jsdelivr.net/npm/[email protected]/build/vega-embed.min'
        }
      });
      require(['vega', 'vega-util', 'vega-lite', 'vega-embed'], function(vega, vegaUtil, vegaLite, vegaEmbed) {
        #{js}
      });
    </script>
  EOS
  ["text/html", output]
end