0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

【Rails】PowerShellでのコントローラ名の一括変換方法

Posted at

コントローラファイルの「class ○○Controller」部分を
「class Public::○○Controller」に修正する作業で、
コマンドで一括で変換する方法を探しました。


1. バックアップを取る

Copy-Item -Path app/controllers/public -Destination app/controllers/public_backup -Recurse

2. 該当フォルダに移動

cd .\app\controllers\public

3. コマンドを実行

Get-ChildItem -Filter '*_controller.rb' | ForEach-Object {
    # ファイル内容をUTF-8エンコーディングで読み込み
    $content = Get-Content $_ -Encoding UTF8

    # class名の変更
    $content = $content -replace 'class (\w+)Controller', 'class Public::$1Controller'

    # UTF-8エンコーディングで書き込み
    Set-Content $_ -Value $content -Encoding UTF8
}

最初下記コードを実行したが、これだとコメントアウトしてた箇所が文字化けしてしまった。
文字化けの原因は、Windows-1252に変更されてしまっていたから。

文字化けしたコード

Get-ChildItem -Filter '*_controller.rb' | ForEach-Object {
    # 各コントローラファイルを処理
    Get-Content $_ | ForEach-Object {
        # クラス名の置換処理
        $_ -replace 'class (\w+)Controller', 'class Public::$1Controller'
    } | Set-Content $_
}

Get-Content はファイルを読み込むとき、システムのロケール設定に従ったエンコーディング(通常、Windowsでは Windows-1252UTF-16)で読み込む。
そのため、UTF-8で保存されているファイルでも、デフォルトのエンコーディングで読み込まれると、コメントアウトなどの非ASCII文字が正しく認識されず、文字化けを引き起こす可能性がある。

Set-Content は、デフォルトで UTF-8 エンコーディングを使用してファイルを上書きする。
しかし、Get-Contentで読み込んだ内容がWindows-1252 や UTF-16で処理された場合、その内容を UTF-8 で書き込むことで文字化けしてしまう。

成功したコード

Get-ChildItem -Filter '*_controller.rb' | ForEach-Object {
    # ファイル内容をUTF-8エンコーディングで読み込み
    $content = Get-Content $_ -Encoding UTF8

    # class名の変更
    $content = $content -replace 'class (\w+)Controller', 'class Public::$1Controller'

    # UTF-8エンコーディングで書き込み
    Set-Content $_ -Value $content -Encoding UTF8
}

コマンドの説明

UTF-8を保ちながら文字化けを防ぎつつ一括変換を行うには、Get-ContentSet-Content コマンドにエンコーディングを指定する必要がある。
PowerShellでは、-Encoding オプションを使用してファイルのエンコーディングを指定できる。

  • Get-Content $_ -Encoding UTF8
    ファイルをUTF-8エンコーディングで読み込む。
  • $content -replace 'class (\w+)Controller', 'class Public::$1Controller'
    クラス名を class Public::○○Controller に変更。
  • Set-Content $_ -Value $content -Encoding UTF8
    UTF-8エンコーディングで変更後の内容を書き込む。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?