Skip to content

Instantly share code, notes, and snippets.

@aidistan
Last active September 5, 2022 01:04
Show Gist options
  • Save aidistan/e8397a4377d411dcc1f36e2805a08fbd to your computer and use it in GitHub Desktop.
Save aidistan/e8397a4377d411dcc1f36e2805a08fbd to your computer and use it in GitHub Desktop.
Convert Notion block objects to markdown
require 'notion-sdk-ruby'
class Notion::Block
def to_md
prefix = ''
suffix = ''
case type
when 'paragraph'
# do nothing
when /heading_(\d)/
prefix = '#' * Regexp.last_match(1).to_i + ' '
self[type]['rich_text'].map { _1['annotations']['bold'] = false } # unbold headings
when 'callout'
# do nothing
when 'quote'
prefix = '> '
when 'bulleted_list_item'
prefix = '- '
when 'numbered_list_item'
prefix = '1. '
when 'to_do'
prefix = to_do['checked'] ? '- [x] ' : '- [ ] '
when 'toggle'
# do nothing
when 'code'
prefix = "```#{code['language'].split.first}\n"
suffix = "\n```"
when 'image'
return "![#{RichText.to_md(image['caption'])}](#{image[image['type']]['url']})"
when 'equation'
return "$$#{equation['expression']}$$"
else
raise 'Unable to convert the block'
end
# Only for types with rich_text, others should return in `case`
prefix + RichText.to_md(self[type]['rich_text']) + suffix
rescue RuntimeError => e
puts "#{e.message}: #{JSON.pretty_generate(to_h)}"
"```json\n#{JSON.pretty_generate(to_h)}\n```"
end
end
class Notion::RichText
ATTRIBUTES = %w[
plain_text href annotations type text mention equation
].each { attr_reader _1 }
def self.to_md(obj)
obj.is_a?(Array) ? obj.map { |item| new(item).to_md }.join : new(obj).to_md
end
def initialize(data)
ATTRIBUTES.each { instance_variable_set("@#{_1}", data[_1]) }
end
def to_md
md = plain_text
# Shortcut for equation
return "$#{md}$" if type == 'equation'
md = "<u>#{md}</u>" if annotations['underline']
md = "`#{md}`" if annotations['code']
md = "**#{md}**" if annotations['bold']
md = "*#{md}*" if annotations['italic']
md = "~~#{md}~~" if annotations['strikethrough']
md = "[#{md}](#{href}){:target=\"_blank\"}" if href
md
end
end
# Your code goes here ...
# Paste followings at the bottom of `convert_notion_to_md.rb`
# Create a client for Notion APIs
client = Notion::Client.new(token: 'PUT_YOUR_TOKEN_HERE'))
# A simplest example
pages = client.databases.query('YOUR_DATABASE_ID')
blocks = client.blocks.children.list(page.first.id)
puts blocks.map(&:to_md).join("\n\n")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment