よく使うRails 6.1で生成ファイルを最小限にするrails newコマンド

環境

Ruby 2.7.2
Rails 6.1.0

最小限の rails new

rails new --minimal -S -J -T --database=postgresql TestApp

--minimal

以下のフレームワークがスキップされる

  • action_cable
  • action_mailbox
  • action_mailer
  • action_text
  • active_job
  • active_storage
  • bootsnap
  • jbuilder
  • spring
  • system_tests
  • turbolinks
  • webpack

-S -J -T オプション

minimalと重複するものもありますが以下

  -S, [--skip-sprockets], [--no-skip-sprockets]              # Skip Sprockets files
      [--skip-spring], [--no-skip-spring]                    # Don't install Spring application preloader
      [--skip-listen], [--no-skip-listen]                    # Don't generate configuration that depends on the listen gem
  -J, [--skip-javascript], [--no-skip-javascript]            # Skip JavaScript files
      [--skip-turbolinks], [--no-skip-turbolinks]            # Skip turbolinks gem
      [--skip-jbuilder], [--no-skip-jbuilder]                # Skip jbuilder gem
  -T, [--skip-test], [--no-skip-test]                        # Skip test files
      [--skip-system-test], [--no-skip-system-test]          # Skip system test files
      [--skip-bootsnap], [--no-skip-bootsnap]                # Skip bootsnap gem

その他オプション

rails new -h で詳細を確認できます

$ rails new -h
Usage:
  rails new APP_PATH [options]

Options:
      [--skip-namespace], [--no-skip-namespace]              # Skip namespace (affects only isolated engines)
      [--skip-collision-check], [--no-skip-collision-check]  # Skip collision check
  -r, [--ruby=PATH]                                          # Path to the Ruby binary of your choice
                                                             # Default: /home/akinov/.rbenv/versions/2.7.2/bin/ruby
  -m, [--template=TEMPLATE]                                  # Path to some application template (can be a filesystem path or URL)
  -d, [--database=DATABASE]                                  # Preconfigure for selected database (options: mysql/postgresql/sqlite3/oracle/sqlserver/jdbcmysql/jdbcsqlite3/jdbcpostgresql/jdbc)
                                                             # Default: sqlite3
      [--skip-gemfile], [--no-skip-gemfile]                  # Don't create a Gemfile
  -G, [--skip-git], [--no-skip-git]                          # Skip .gitignore file
      [--skip-keeps], [--no-skip-keeps]                      # Skip source control .keep files
  -M, [--skip-action-mailer], [--no-skip-action-mailer]      # Skip Action Mailer files
      [--skip-action-mailbox], [--no-skip-action-mailbox]    # Skip Action Mailbox gem
      [--skip-action-text], [--no-skip-action-text]          # Skip Action Text gem
  -O, [--skip-active-record], [--no-skip-active-record]      # Skip Active Record files
      [--skip-active-job], [--no-skip-active-job]            # Skip Active Job
      [--skip-active-storage], [--no-skip-active-storage]    # Skip Active Storage files
  -P, [--skip-puma], [--no-skip-puma]                        # Skip Puma related files
  -C, [--skip-action-cable], [--no-skip-action-cable]        # Skip Action Cable files
  -S, [--skip-sprockets], [--no-skip-sprockets]              # Skip Sprockets files
      [--skip-spring], [--no-skip-spring]                    # Don't install Spring application preloader
      [--skip-listen], [--no-skip-listen]                    # Don't generate configuration that depends on the listen gem
  -J, [--skip-javascript], [--no-skip-javascript]            # Skip JavaScript files
      [--skip-turbolinks], [--no-skip-turbolinks]            # Skip turbolinks gem
      [--skip-jbuilder], [--no-skip-jbuilder]                # Skip jbuilder gem
  -T, [--skip-test], [--no-skip-test]                        # Skip test files
      [--skip-system-test], [--no-skip-system-test]          # Skip system test files
      [--skip-bootsnap], [--no-skip-bootsnap]                # Skip bootsnap gem
      [--dev], [--no-dev]                                    # Set up the application with Gemfile pointing to your Rails checkout
      [--edge], [--no-edge]                                  # Set up the application with Gemfile pointing to Rails repository
      [--master], [--no-master]                              # Set up the application with Gemfile pointing to Rails repository master branch
      [--rc=RC]                                              # Path to file containing extra configuration options for rails command
      [--no-rc], [--no-no-rc]                                # Skip loading of extra configuration options from .railsrc file
      [--api], [--no-api]                                    # Preconfigure smaller stack for API only apps
      [--minimal], [--no-minimal]                            # Preconfigure a minimal rails app
  -B, [--skip-bundle], [--no-skip-bundle]                    # Don't run bundle install
  --webpacker, [--webpack=WEBPACK]                           # Preconfigure Webpack with a particular framework (options: react, vue, angular, elm, stimulus)
      [--skip-webpack-install], [--no-skip-webpack-install]  # Don't run Webpack install

Runtime options:
  -f, [--force]                    # Overwrite files that already exist
  -p, [--pretend], [--no-pretend]  # Run but do not make any changes
  -q, [--quiet], [--no-quiet]      # Suppress status output
  -s, [--skip], [--no-skip]        # Skip files that already exist

Rails options:
  -h, [--help], [--no-help]        # Show this help message and quit
  -v, [--version], [--no-version]  # Show Rails version number and quit

Description:
    The 'rails new' command creates a new Rails application with a default
    directory structure and configuration at the path you specify.

    You can specify extra command-line arguments to be used every time
    'rails new' runs in the .railsrc configuration file in your home directory,
    or in $XDG_CONFIG_HOME/rails/railsrc if XDG_CONFIG_HOME is set.

    Note that the arguments specified in the .railsrc file don't affect the
    defaults values shown above in this help message.

Example:
    rails new ~/Code/Ruby/weblog

    This generates a skeletal Rails installation in ~/Code/Ruby/weblog.

レスポンシブサイトでlazysizesを使い画像遅延読み込みをした時のCore Web Vitals CLS対策

Core Web Vitalsの値、気にしてますか? レスポンシブでCLS対策をする時の対応を書きます。

CLSとは?

Cumulative Layout Shift は、ページがどのくらい安定しているように感じられるかを表します。視覚的な安定性を測定し、表示されるページ コンテンツにおける予期しないレイアウトのずれの量を定量化します。

developers-jp.googleblog.com

画像の読み込みや、コンテンツの遅延読み込みなどでサイトの要素がズレる量のことです。 基本的には画像サイズを指定してあげることでズレはなくなります。

画像遅延読み込みとの兼ね合い

lazysizesというプラグインを使い画像遅延読み込みをしていますが、読み込まれるまで1x1pxの透過画像を置いておくのがスタンダードです。

<img src="data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw==" data-src="本来の画像URL" class="lazyload" width="200" height="100">

github.com

レスポンシブで1x1px透過画像を先読みする場合の不具合

レスポンシブにしたいと、画像を width: 100%; height: auto; にすると
読込中 1x1px 画像のアスペクト比を保持して横100%になってしまいます。

読み込まれるまで高さがwidthと同じになってしまう
<img src="data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw==" data-src="本来の画像URL" class="lazyload" width="200" height="100">

<style>
  img {
    width: 100%;
    height: auto;
  }
</style>

サンプル レスポンシブサイトでlazysizesを使い画像遅延読み込みをした時のCore Web Vitals CLS対策 サンプル

このサンプルでは1枚目の画像も 1:1 の高さを保持してしまっているため画像読み込み後にズレが生じてCLSが0.095になっています。
※サンプルなのでそこまで悪い数字ではないですが f:id:kuronekopunk:20201211231400p:plain

対策

  • imgタグのwidth, heightは幅320pxの時のアスペクト比で入れる
  • height: auto; はlazyloadが完了してから設定する

下記のようになります。

<img src="data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw==" data-src="本来の画像URL" class="lazyload" width="320" height="160">

<style>
  img {
    width: 100%;
  }
  /* lazyload完了後に付与されるクラス */
  img.lazyloaded {
    height: auto;
  }
</style>

サンプル レスポンシブサイトでlazysizesを使い画像遅延読み込みをした時のCore Web Vitals CLS対策 サンプル

CLSが0.009になりました。

f:id:kuronekopunk:20201211231454p:plain

注意

imgタグのwidth, heightは幅320pxの時のアスペクト比で入れる

というのはLighthouseのmobileで計測する時のブラウザ幅です。
違うブラウザ幅だとCLSのガタつきが発生するためユーザーにとって最適とは言えません。
事前にアスペクト比が分かっているならpadding-topを%で指定して先にサイズを確保しておくなどありますが、運用面でコストが高くなってしまいます。
ケースに合った対応を心がけましょう。

WSLでChromedriverを使えるようにする

chromedriverのDL

公式サイトから必要なバージョンをDLします。

f:id:kuronekopunk:20201129142705p:plain

DL後、zipを解凍したらWindowsTerminalでWSLの /bin/ に移動

# CドライブのDownloadsにchromedriverがある
sudo mv chromedriver /bin/cromedriver
# 実行権限の付与
sudo chown 755 /bin/chromedriver

f:id:kuronekopunk:20201129142903p:plain

chromedriver のバージョンを確認

$ chromedriver -v
ChromeDriver 86.0.4240.22 (398b0743353ff36fb1b82468f63a3a93b4e2e89e-refs/branch-heads/4240@{#378})

参考

WSL上でRspecのSystem Specを使った時のエラー - Qiita

「Selenium::WebDriver::Error::WebDriverError: unable to connect to chromedriver 127.0.0.1:9515」または「Selenium::WebDriver::Error::UnknownError: unknown error: cannot find Chrome binary」のエラーに対応する - Qiita

WindowsのLocal by Flywheelで作ったWordPressにシンボリックリンクを貼り別ディレクトリのthemesデータを同期させる

新規でWP環境を作るだけならLocalをインストールするだけなのですがすでにあるプロジェクトのthemesだけを同期させたいため特殊な対応をしました。

まずは公式ドキュメント通りLocalのインストール、WPの作成をします。 localwp.com

themesを同期させる

昔のLocalだとvolumesという設定でファイル同期ができましたが今はシンボリックリンクを貼る必要があるよう

[WordPress] ”Local by Flywheel”でシンボリックリンクを作成する方法

Windows PowerShellを管理者で起動しシンボリックリンクを貼ります

# ローカルにある参照したいthemes
# "C:\Users\user_name\workspace\wordpress\wp-content\themes\"

# LocalでインストールしたWPのディレクトリ
# "C:\Users\user_name\Local Sites\nisso\app\public"
New-Item -Value "C:\Users\user_name\workspace\wordpress\wp-content\themes\" -Path "C:\Users\user_name\Local Sites\site_name\app\public\themes" -ItemType SymbolicLink

※既にインストールしたWPのthemesがある場合は削除しておく必要があります。

エクスプローラーでシンボリックリンクがあるのを確認 f:id:kuronekopunk:20201127174455p:plain

WSL Elasticsearchの起動ができない java.lang.IllegalArgumentException: Plugin [analysis-kuromoji] was built for Elasticsearch version 7.8.0 but version 7.10.0 is running

こんなエラーが出た

java.lang.IllegalArgumentException: Plugin [analysis-kuromoji] was built for Elasticsearch version 7.8.0 but version 7.10.0 is running

$ sudo service elasticsearch restart
 * Starting Elasticsearch Server                                                                                        uncaught exception in thread [main]
java.lang.IllegalArgumentException: Plugin [analysis-kuromoji] was built for Elasticsearch version 7.8.0 but version 7.10.0 is running
        at org.elasticsearch.plugins.PluginsService.verifyCompatibility(PluginsService.java:352)
        at org.elasticsearch.plugins.PluginsService.loadBundle(PluginsService.java:622)
        at org.elasticsearch.plugins.PluginsService.loadBundles(PluginsService.java:479)
        at org.elasticsearch.plugins.PluginsService.<init>(PluginsService.java:168)
        at org.elasticsearch.node.Node.<init>(Node.java:346)
        at org.elasticsearch.node.Node.<init>(Node.java:289)
        at org.elasticsearch.bootstrap.Bootstrap$5.<init>(Bootstrap.java:227)
        at org.elasticsearch.bootstrap.Bootstrap.setup(Bootstrap.java:227)
        at org.elasticsearch.bootstrap.Bootstrap.init(Bootstrap.java:393)
        at org.elasticsearch.bootstrap.Elasticsearch.init(Elasticsearch.java:170)
        at org.elasticsearch.bootstrap.Elasticsearch.execute(Elasticsearch.java:161)
        at org.elasticsearch.cli.EnvironmentAwareCommand.execute(EnvironmentAwareCommand.java:86)
        at org.elasticsearch.cli.Command.mainWithoutErrorHandling(Command.java:127)
        at org.elasticsearch.cli.Command.main(Command.java:90)
        at org.elasticsearch.bootstrap.Elasticsearch.main(Elasticsearch.java:126)
        at org.elasticsearch.bootstrap.Elasticsearch.main(Elasticsearch.java:92)
For complete error details, refer to the log at /var/log/elasticsearch/elasticsearch.log
                                                                                                                 [fail]

プラグインの対応バージョンが違うらしい
Elasticsearchをアップデートだけしてプラグインが古いままのよう
一旦removeしてインストールし直す

sudo /usr/share/elasticsearch/bin/plugin remove analysis-kuromoji
sudo /usr/share/elasticsearch/bin/plugin install analysis-kuromoji

起動成功

$ sudo service elasticsearch restart
 * Starting Elasticsearch Server                                                                                 [ OK ]