パンプキンスパイスラテ

IT系のことが多めの日記帳です

あるディレクトリのHTMLファイルをすべて1ファイルのHTMLに書き換えるスクリプト

タイトルだけじゃなんのこっちゃ。
とあるレンタルサーバーがありまして、404ページはいじれない、.htaccessも使えないという状況で、サイトを閉鎖したいということになり、サイト閉鎖のお知らせを表示させたいんだけど、ユーザーがアクセスしたら404ページにはさせたくない、なんてことになったとしたら。
最後の手段としては、すべてのページをサイト閉鎖のお知らせページに差し替えるしか無さそう。。。
ってことでサクっとスクリプトを書いてみた。
今後(絶対無いと思うけど)、必要になった時の自分用メモとして載せておく。

require 'find'

open("base.html") {|source|

  base_source = source.read

  # コピー先ディレクトリを作成
  Dir::mkdir("copy") unless File.exist?("copy")

  # ./document 以下のファイルを列挙する。
  Find.find('./document') {|f|

    # ./ を copy/ に置換する
    target = f.sub(/\.\//,"copy/")

    if target =~ /\.html$/ then
      open(target, "w") {|dest|
        dest.write(base_source)
      }
      puts target  # 画面出力
    else

      # . が無い=ディレクトリ
      unless target =~ /\./ then
        # ディレクトリ無かったら生成
        Dir::mkdir(target) unless File.exist?(target)
      end

    end
  }
}

これで、実行スクリプトをscript.rb、ベースとなるHTMLをbase.html、対象のディレクトリをdocumentとして、下記のように配置する。

  • script.rb
  • base.html
  • document
    • a.html
    • b.html
    • icon.jpg
    • style.css
    • dir
      • aa.html
      • bb.html


そして実行。

ruby script.rb

結果。

copy/document/a.html
copy/document/b.html
copy/document/dir/aa.html
copy/document/dir/bb.html

これですべてのファイルがbase.htmlの中身に差し替えできました。