見出し画像

コメントアウトが無効な記述

●コメントアウトされているのに、なぜ動く?

app/assets/stylesheets/application.css

/*
* This is a manifest file that'll be compiled into application.css, which will include all the files
* listed below.
*
* Any CSS and SCSS file within this directory, lib/assets/stylesheets, or any plugin's
* vendor/assets/stylesheets directory can be referenced here using a relative path.
*
* You're free to add application-wide styles to this file and they'll appear at the bottom of the
* compiled file so the styles you add here take precedence over styles defined in any other CSS/SCSS
* files in this directory. Styles in this file should be added after the last require_* statement.
* It is generally better to create a new file per style scope.
*
*= require_tree .
*= require_self
*/

すべての行に、コメントアウトが適応されている。
しかし、「*=require_tree」がなぜ機能しているか疑問に思った。

●仮説と検証

application.cssの「*=require_tree」は、
ディレクトリ以下のCSSをすべて読み込む記述。

そのディレクトリに配置されているCSSは、
ブラウザで見る限り正確に反映されている。

また、ビューのHTMLファイル、
レイアウトテンプレートファイル(application.html.erb)、
どちらからも直接参照の記述はしていない。

つまり、
レイアウトテンプレートファイル(application.html.erb)により、
マニフェストファイル(application.css)が読まれ、
マニフェスト内の記述(*= require_tree .)により、配置したファイルが読まれる仕組みが正常に動作しているということになる。。



また、同様のことがapp/assets/config/manifest.jsでも起きている。

//= link_tree ../images
//= link_directory ../stylesheets .css

「= link_tree ../images」がコメントアウトされているが、
app/assets/images以下に配置した画像も
imgタグヘルパーにて、パス指定なしのファイル名のみで適応されている。

image_tagは、デフォルトではpublic/images以下から読み込まれる(※)ため
「= link_tree ../images」が機能しているといえる。

Railsガイドより

image_tagは、デフォルトでは、ファイルはpublic/images以下から読み込まれます。


ものは試し・・・ということで、
コメントアウトを外す、またはコメント外へコードを移動させると、
コード色が変化し、機能してるよ!の色になった。

つまり、コメントアウトは間違いなく行われているし、
有効な記述状態ではない。

だが、機能していることから考えると、
「=」が入っているとコメントアウト無効になるのか?と仮説を立てた。

実験するためにrubyで下記コードを記述。

puts "コメントアウト"

このままの状態で、ファイルを実行するともちろん「コメントアウト」と表示された。

次に、下記に変更して実行。

#puts "コメントアウト"
#=puts "コメントアウト"

結果は、出力なし。仮説は違ったようだ。

●メンター質問後

これは、コメントアウトされていても機能する!
というように裏でなっているから、という事だった。

確かに、これらはデフォルトの記述なので
そういった設定も可能だと思える。

コマンドで自動生成されるファイル、
そのファイルにデフォルトであるガイド以外の記述には、
そういった設定があるというケースも、頭の中に入れておくといいなと思った。

今回のように、明らかにルールを無視していたりするものは、
(コメントアウトなのに機能している)
裏で設定が働いているのではないだろうか?と、
考えるのが有効そうだと感じた。