← View all my writings

Perron_introduction

Published at 2026/03/24

Perron_introduction

1. アプリ作成

rails new appname --minimal -T -O -m https://perron.railsdesigner.com/library/new/template.rb

Markdownパーサーを聞かれるので kramdown を入力:

Which markdown parser would you like to use? kramdown

2. ディレクトリ移動

cd appname

3. テンプレート導入

rails app:template LOCATION='https://perron.railsdesigner.com/library/personal-blog/template.rb'

4. ビューの不要な記述を削除

app/views/shared/_navigation.html.erb から下記を削除

  <ul class="flex items-center gap-x-4 sm:gap-x-6">
    <%= render partial: "shared/navigation/item", collection: items %>
  </ul>

5. outputフォルダを.gitignoreから削除

# grep して output が表示されるかの確認
cat .gitignore|grep output
# output が書かれてたら削除して保存
nano .gitignore
# nano で開いてoutput を削除して保存
cat .gitignore|grep output

6. Timezone修正

app/config/application.rb を修正

    config.time_zone = "Tokyo"

7. CSSを整える

app/assets/tailwind/application.css に追記

@layer component {
  .content {
    /* 既存のスタイル... */

    @apply [&_pre]:bg-gray-100 [&_pre]:relative;
    @apply [&_pre]:pt-8; /* 言語ラベルの分の余白 */
  }
}

8. コードブロックの調整

8-1. 複数行表示

kramdown はデフォルトの設定だとコードブロックが1行になる。
GFM(GitHub Flavored Markdown)モードにするとコードブロックの改行が保持される。

config/initializers/perron.rb に以下を追加する。

config.markdown_options = { input: "GFM" }

kramdownでGFMを使うには kramdown-parser-gfm gemが必要
下記を実行してインストール

bundle add kramdown-parser-gfm

8-2. コピーボタン設置

app/javascript/code_blocks.js を作成

document.addEventListener("DOMContentLoaded", () => {
  document.querySelectorAll("pre code[class*='language-']").forEach((code) => {
    const pre = code.parentElement;
    const lang = code.className.replace("language-", "");

    // 言語ラベル
    const label = document.createElement("span");
    label.textContent = lang;
    label.className = "absolute top-0 left-3 text-xs text-gray-400 font-sans";
    label.style.top = "0.25em";
    label.style.marginTop = "0.25em";
    pre.appendChild(label);

    // コピーボタン
    const button = document.createElement("button");
    button.textContent = "Copy";
    button.className = "absolute top-0 right-3 text-xs text-gray-400 font-sans hover:text-gray-700";
    button.style.top = "0.25em";
    button.style.marginTop = "0.25em";
    button.addEventListener("click", () => {
      navigator.clipboard.writeText(code.textContent).then(() => {
        button.textContent = "Copied!";
        setTimeout(() => button.textContent = "Copy", 2000);
      });
    });
    pre.appendChild(button);
  });
});

8-3. importmap の導入

rails new のときに –minimal していると importmap のインストールがスキップされる
JavaScript を使用する場合は、自分で入れる必要がある

8-3-1. importmap の install

bundle add importmap-rails
rails importmap:install

8-3-2. config/importmap.rb にJSファイルを登録

pin "application"
pin "code_blocks"

8-3-3. app/javascript/application.js に記載

import "code_blocks"

9. 起動して確認

bin/dev

Comments

What do you think? Got ideas or suggestions? Let me know below.

Comments are powered by Chirp Form