TableBlock, TableRowBlock: NotionRubyMapping 解説 (27)

はじめに

NotionRubyMapping 解説の第27回目です。今回は表全体を管理する TableBlock と単一の行を管理する TableRowBlock の組み合わせでシンプルテーブルを実現します。今日の作業ページはこちらです。

hkob.notion.site

あらかじめページを取得しておきます。

irb(main):002> page = Page.find "https://hkob.notion.site/TableBlock-TableRowBlock-27-59b3014991a9456db3f35dccd44e5861?pvs=4"
=> NotionRubyMapping::Page-59b3014991a9456db3f35dccd44e5861

TableBlock

ColumnListBlock と同様に TableBlock のコンストラクタでは、Array の Array を渡すだけで内部で TableRowBlock を自動的に設定してくれます。

irb(main):003> tb = page.append_block_children TableBlock.new(table_width: 3, table_rows: [%w[2 9 4], %w[7 5 3], %w[6 1 8]])
=> NotionRubyMapping::TableBlock-1e3b68c87c0841f7b92f7286cef7aad2

実行した結果以下のようなシンプルテーブルが用意されました。

魔法陣

この TableBlock の子ブロックを確認すると以下のように TableRowBlock が入っています。

irb(main):004> tb.children.to_a
=>
[NotionRubyMapping::TableRowBlock-60d28683d7ec4723839762ef526ead84,
 NotionRubyMapping::TableRowBlock-c67e67d80c0a4a578e9cbac0c032b605,
 NotionRubyMapping::TableRowBlock-aa7366e90aaf4481a179bd8b556cac17]

TableRowBlock は作成はできるのですが、内容が編集できるようにしていませんでした。 @cells に RichTextArray が入っているだけなので、cells でこれが取得できるようになっていればいいですね。こちらも後で修正しておきます。

irb(main):012> tb.children.to_a.first.cells
(irb):12:in `<main>': undefined method `cells' for an instance of NotionRubyMapping::TableRowBlock (NoMethodError)
  from <internal:kernel>:187:in `loop'
    from /Users/hkob/.rbenv/versions/3.3.0/lib/ruby/gems/3.3.0/gems/irb-1.11.1/exe/irb:9:in `<top (required)>'
  from /Users/hkob/.rbenv/versions/3.3.0/bin/irb:25:in `load'
  from /Users/hkob/.rbenv/versions/3.3.0/bin/irb:25:in `<main>'

先ほどの例では Cell の中が単一テキストでしたが、Cell の部分は text_info に相当する配列を渡すこともできます。また、text_column_headertext_row_header を true にすることでヘッダ列やヘッダ行を設定することができます。

irb(main):013> tb2 = page.append_block_children TableBlock.new(table_width: 2, h
as_column_header: true, has_row_header: true, table_rows: [
irb(main):014*   %w[Services Account],
irb(main):015*   [
irb(main):016*     "Twitter",
irb(main):017*     ["hkob\n", TextObject.new("profile", "href" => "https://twitt
er.com/hkob/")],
irb(main):018*   ],
irb(main):019*   [
irb(main):020*     "GitHub",
irb(main):021*     ["hkob\n", TextObject.new("repositories", "href" => "https://
github.com/hkob/")],
irb(main):022*     ]
irb(main):023> ])
=> NotionRubyMapping::TableBlock-ca1aebc5625e457aadaa85269100e6be

ヘッダ列・ヘッダ行が設定されているだけでなく、Cell内で複数のTextObject が設定されていることもわかります。

プロフィール表

おわりに

今回は TableBlock を解説してみました。作成時には配列を渡すことで TableRowBlock を自動で設定してくれます。こちらはまだ作りかけで編集などの機能が実装されていませんでした。近いうちにこれらも改修しておきたいと思います。

TableBlock や TableRowBlock のマニュアルはまだ書いていませんでした。

NotionRubyMapping解説