ЯoomeR

プログラミング~実装とエラー解決と、時々、AI~

Railsファイル辞典(binディレクトリ編)

rails newで生成されるファイルが「何のためにあるのか?」を徹底解説。

ディレクトリの階層を再現している。

※本記事はRailsのver6系統を使用している。

binディレクト

binbinaryの略である。

bundle
rails
rake
setup
spring
webpack
webpack-dev-server
yarn

これらは'binstub'と呼ばれるものである。

例えば、bin/railsの中身は以下の通りである。

#!/usr/bin/env ruby
begin
  load File.expand_path("../spring", __FILE__)
rescue LoadError => e
  raise unless e.message.include?("spring")
end
APP_PATH = File.expand_path("../config/application&", __dir__)
require_relative "../config/boot"
require "rails/commands"

最後の行で呼び出しているrails/commandsを見てみよう。

# frozen_string_literal: true

require "rails/command"

aliases = {
  "g"  => "generate",
  "d"  => "destroy",
  "c"  => "console",
  "s"  => "server",
  "db" => "dbconsole",
  "r"  => "runner",
  "t"  => "test"
}

command = ARGV.shift
command = aliases[command] || command

Rails::Command.invoke command, ARGV

ここでよく使うアルファベット「d,c,s...」を定義している。

これによって「rails s→rails server」と判断している。

他にもrailsに関する様々な設定をしているため、bin/railsを削除するとrailsコマンドが使用できなくなる