Sha256: 3c0bb80e146430a4e562a2b8c9f784b5a5c7805a5b8ee03ee507e46cc12f58ed

Contents?: true

Size: 1.88 KB

Versions: 3

Compression:

Stored size: 1.88 KB

Contents

# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

require "tempfile"

module JekyllJupyterNotebook
  class Converter < Jekyll::Converter
    def matches(ext)
      ext == ".ipynb"
    end

    def output_ext(ext)
      ".html"
    end

    def convert(content)
      config = @config["jupyter_notebook"] || {}

      html = convert_notebook(content)
      html.sub!(/<link.+?href="custom.css">/, "")
      case config["content"] || "html"
      when "html"
      when "body"
        html.sub!(/\A.*?<\/title>/m, "")
        html.sub!(/<\/head>/, "")
        html.sub!(/<body>/, "")
        html.sub!(/<\/body>.*?\z/m, "")
      when "body-without-style"
        html.sub!(/\A.*?<body>/m, "")
        html.sub!(/<\/body>.*?\z/m, "")
      end
      html
    end

    private
    def convert_notebook(content)
      notebook = Tempfile.new(["jekyll-jupyter-notebook", ".ipynb"])
      notebook.print(content)
      notebook.close
      IO.pipe do |input, output|
        pid = spawn("jupyter",
                    "nbconvert",
                    "--to", "html",
                    "--stdout",
                    notebook.path,
                    :out => output)
        begin
          output.close
          html = nil
          read_thread = Thread.new do
            html = input.read
          end
          read_thread.join
          html
        ensure
          Process.waitpid(pid)
        end
      end
    end
  end
end

Version data entries

3 entries across 3 versions & 1 rubygems

Version Path
jekyll-jupyter-notebook-0.0.5 lib/jekyll-jupyter-notebook/converter.rb
jekyll-jupyter-notebook-0.0.4 lib/jekyll-jupyter-notebook/converter.rb
jekyll-jupyter-notebook-0.0.3 lib/jekyll-jupyter-notebook/converter.rb