STUDY MEMO

学習のメモ書き

postCSS使用時、src/index.cssに@tailwind baseを書こうとしたら"Unknown at rule"のwarningが出た時の対処

問題

tailwindを使ってみようと思ったら、app/src/直下に作成したindex.cssファイルで"Unknown at rule"のwarningが出た。 ディレクトリ構造としては app/src直下構造は以下の通り。

対処

調べてみたところ、拡張機能を入れればOKと書いてあったのでVSCodeに以下の拡張機能を入れたところ解決した。 marketplace.visualstudio.com

参考資料

qiita.com

< コマンド > PostgreSQL関連

※ Homebrewで管理していることが前提

コマンドリスト

よく使うものをまとめた。

バージョン確認

$ psql --version

PostgreSQLを起動

$ brew services start postgresql

[sudo] brew services start (|-all): Start the service immediately and register it to launch at login (or boot).

PostgreSQLを停止

$ brew services stop postgresql

[sudo] brew services stop (|-all): Stop the service immediately and unregister it from launching at login (or boot).

現在の運用しているbrewのサービスの一覧を取得

ここでPostgreSQLが動いているか確認できる。

$ brew services list

[sudo] brew services [list]: List all managed services for the current user (or root).

引用

github.com

<VSCode> erbファイルでsnippetを使用する際のトリガー一覧メモ

snippetとは

スニペットとは、一般的には「切れ端」「断片」という意味の英語である。IT用語としては、プログラミング言語の中で簡単に切り貼りして再利用できる部分のこと、または、検索エンジンによる検索結果の一部として表示される、Webページの要約文のことである。 https://www.weblio.jp/content/コードスニペット

一覧

トリガー snippets
pe <%= %>
pc <%# %>
if <% if %>...<% end %>
ife <% if %>...<% else %>...<% end %>
else <% else %>
elsif <% elsif %>
unless <% unless %>...<% end %>
end <% end %>
it <%= image_tag ..., ... %>
st <%= submit_tag ..., ... %>
tft <%= text_field_tag ..., ... %>
pft <%= password_field_tag ..., ... %>
lblt <%= label_tag ..., ... %>
lt <%= link_to ..., ... %>
each `<% @things.each do
ff `<%= form_for(@ ) do
t <%= t('@') %>

使用したVSCode拡張機能

ERB-VSCode-Snippets - Visual Studio Marketplace

github

GitHub - matthewrobertson/ERB-Sublime-Snippets: A collection of sublime text snippets useful for coding ERB templates

<Ruby on Rails> slimを使うときに使うgemやサイト

slimを導入するときに使うgem

gem 'slim'

https://github.com/slim-template/slim

htmlまたはhtml.erbをslimへ変換するgem

gem 'html2slim'

https://github.com/slim-template/html2slim

generatorが生成するviewファイルをslimにするgem

gem "slim-rails"

https://github.com/slim-template/slim-rails

htmlをslimへ変換するサイト

https://html2slim.herokuapp.com/

<Ruby on Rails> rails new時にPostgreSQLに対応させるようにする

いつも忘れるのでメモ。

以下のコマンドを実行することで、アプリ作成時に自動でPostgreSQLに対応するように、database.ymlをが作成される。

rails new アプリ名 —database=postgresql

https://railsguides.jp/command_line.html#データベースとソースコード管理システムとrails

< Heroku エラー編 > ActiveSupport::MessageEncryptor::InvalidMessage

発生したエラー

remote:        Running: rake assets:precompile
remote:        rake aborted!
remote:        ActiveSupport::MessageEncryptor::InvalidMessage: ActiveSupport::MessageEncryptor::InvalidMessage
remote:        /tmp/build_abc824e5/vendor/bundle/ruby/3.0.0/gems/activesupport-6.1.3.2/lib/active_support/message_encryptor.rb:203:in `rescue in _decrypt'
...
remote:        
remote:        Caused by:
remote:        OpenSSL::Cipher::CipherError: 
remote:        /tmp/build_abc824e5/vendor/bundle/ruby/3.0.0/gems/activesupport-6.1.3.2/lib/active_support/message_encryptor.rb:198:in `final'

https://docs.ruby-lang.org/ja/latest/class/OpenSSL=3a=3aCipher=3a=3aCipherError.html から、鍵関係のエラーということがわかったので、

EDITOR=vim rails credentials:show

を実行すると

ctiveSupport::MessageEncryptor::InvalidMessageが発生。

https://github.com/rails/rails/issues/31397

から、以下の対処を実行。

対処

master.keyとcredentials.yml.encを作成しなおして、

heroku config:set RAILS_MASTER_KEY=`cat config/master.key`

でセットし直した。

< Ruby > &、&&、I、||について

以前の投稿を手直し

&

集合の積演算。

両方の配列に含まれる要素を含んだ新しい配列を返し、重複する要素は削除される。

要素の重複判定:Objectクラスのインスタンスメソッドeql?により行われる。

https://i.gyazo.com/51ca3d2479f640c7812a04c85017285c.png

&&

左辺を評価し、結果が偽であった場合はnilかfalseを返す。左辺の評価結果が真であった場合には右辺を評価しその結果を返す。

要するに、

aがtrue:bへ進んでbの結果を返す

aがfalseまたはnil:aの結果を返す

例:a && b

# aがtrueの時
a, b = true, 2
a && b # => 2

# aがfalseの時
a && b # => false

使い方の例:新世界編のルフィとゾロの年齢(ネット調べ)

Luffy = 19
Zoro = 21

if Luffy >= 20 && Zoro >= 20 #ルフィは19なので次の処理へ
    puts "二人とも成人"
elsif Luffy < 20 && Zoro >= 20 #左辺がtrueのため右辺へ進み、右辺でもtrueが返る
    puts "ルフィは未成年"
else
    puts "二人とも未成年"
end

# 結果
# ルフィは未成年

|

集合の和演算。

両方の配列に含まれる要素を含んだ新しい配列を返し、重複する要素は削除される。

要素の重複判定は、Objectクラスのインスタンスメソッドであるeql?またはhashで行われる。

https://i.gyazo.com/00105a0a4f938e3d6074d7db9f14c93e.png

||

左辺を評価し、結果が真(true)であった場合にはその値を返す。 左辺の評価結果が偽(false)であった場合には右辺を評価しその評価結果を返す。

要するに、

aがtrue:aの結果を返す

aがfalseまたはnil:bへ進んでbの結果を返す

a || b

# aがtrueの時
a,b = true,2
a||b # => true

# aがfalseの時
a,b = false,2
a||b # => 2

&&と||

&&と||を表にすると下表のようになる。 これを図にすると、

https://i.gyazo.com/a9ae4be6bb440b7f8231e1c2a38497b0.png

https://i.gyazo.com/665aafcf0ef82c53c9bc67229502fb29.png

この図からみると、&&は以下のようになる。

https://i.gyazo.com/46b6afc24e7fbceffd8d43680580c312.png

また、||は以下のようになる。

https://i.gyazo.com/f1260e6a87e16da7ce5317385b674d17.png

参考文献

https://www.amazon.co.jp/ゼロからわかる-Ruby-超入門-かんたんIT基礎講座-五十嵐/dp/4297101238:title

https://docs.ruby-lang.org/ja/latest/method/Array/i/=26.html

https://docs.ruby-lang.org/ja/latest/method/Array/i/=7c.html

https://docs.ruby-lang.org/ja/latest/doc/spec=2foperator.html#and

https://docs.ruby-lang.org/ja/latest/doc/spec=2foperator.html#or

<VS code> rubyの自動補完機能

拡張機能prettierとprettier+をインストールする。

ドキュメントによると、rubyはpluginでの対応となるため、yarnやnpmでインストールする。

command + ,で設定を開いてsetting.jsonを検索し、ファイルを開いて以下を記載する。

"[ruby]": {
    "editor.defaultFormatter": "esbenp.prettier-vscode",
    "editor.formatOnSave": true
  },

VScodeを再起動し、rbファイルを開いた時に、Prettierが適応されていることを確認。

https://i.gyazo.com/eea2ced844e9c464fd5d7b5161a5cfa8.png

command + ,で再び設定を開き、format on saveにチェックをつける。

https://i.gyazo.com/64a008827130a2b8ed7baf596a2ba21e.png

これでsave時にインデント調整されるはず。

参考

https://github.com/prettier/plugin-ruby

https://qiita.com/tomtang/items/624ad37219fe8c1df1bd

< Heroku > herokuのステージング環境とプロダクション環境のCLIの紐付け

以下のコマンドでstagingをデフォルトのherokuリモートにする。

$ git config heroku.remote staging

.git/configファイルに以下が追記される。

[heroku]
  remote = staging

この記載がされることで、CLIコマンドがデフォルトでstagingアプリを管理するようになる。

以下のようにremoteを追加されていれば、

$ heroku git:remote -a アプリ名(staging)
$ heroku git:remote -r production -a アプリ名(production)

.git/configファイルは以下のようになる。

[heroku]
    remote = staging
[remote "staging"]
    url = https://git.heroku.com/アプリ名-staging.git
    fetch = +refs/heads/*:refs/remotes/staging/*
[remote "production"]
    url = https://git.heroku.com/アプリ名.git
    fetch = +refs/heads/*:refs/remotes/production/*

上記という前提があると、以下のコマンドを実行することで、productionアプリに対して実行ができる。

$ heroku logs -t -r production

参考文献

アプリの複数の環境の管理 | Heroku Dev Center

< Heroku エラー編 > Error: Missing required flag

stagingからproductionにpromoteしようとした時、以下のエラーが出た。

$ heroku pipelines:promote
›   Error: Missing required flag:
›     -a, --app APP  app to run command against
›   See more help with --help

flagがない、ということでgit remote -vを確認するとherokuのサーバーと紐づいてなかった。

そのため上記エラーが発生した模様。

以下のコマンドで紐付けをした。

$ heroku git:remote -a アプリ名

<Ruby on Rails> seedの分割

分割理由

DBの初期データ投入のためにseedファイルを使用したが、量が多いので分割して見やすくしたかった。

1の方法がスマートだが、2の方法も一応記入しておく。

共通

dbにseedsディレクトリを作成

$ mkdir db/seeds

seedsディレクトリの下に任意のseedファイルを作成

$ touch db/seeds/result.rb

方法1. seed.rbにseedsディレクト

seeds.rbにseedsディレクトリ以下を読み込むように設定

Dir.glob(File.join(Rails.root, 'db', 'seeds', '*.rb')) do |file|
  load(file)
end

これにより、bundle exec rails db:seedでseedsディレクトリ以下のrbファイルが読み込まれ、初期データを一度に作成することができる。

方法2. rakeタスクとして保存

rakeタスクに実行方法を記載

lib/tasks/seed.rakeを作成

$ mkdir lib/tasks/seed.rake
Dir.glob(File.join(Rails.root, 'db', 'seeds', '*.rb')).each do |file|
  desc "Load the seed data from db/seeds/#{File.basename(file)}."
  task "db:seed:#{File.basename(file).gsub(/\..+$/, '')}" => :environment do
    load(file)
  end
end

●File.joinFile.join("a","b")と書いた時、"a/b"となる。そのため、File.join(Rails.root, 'db', 'seeds', '*.rb')の部分は

pry(main)> Rails.root
=> #<Pathname:/Users/user_name/workspace/runteq/PF/kinoko2>

ということから、Users/user_name/workspace/runteq/PF/kinoko2/db/seeds/*rbを指定したこととなる。

●Dir.grobは、ワイルドカードの展開を行い、パターンにマッチするファイル名を文字列の配列として返すので、

pry(main)> Dir.glob(File.join(Rails.root, 'db', 'seeds', '*.rb'))
=> ["/Users/user_name/workspace/runteq/PF/kinoko2/db/seeds/result.rb"]

となる。

seedsディレクトリ内に、別のファイルwise_saying.rbがあるとすると、

pry(main)> Dir.glob(File.join(Rails.root, 'db', 'seeds', '*.rb'))
=> ["/Users/user_name/workspace/runteq/PF/kinoko2/db/seeds/result.rb",
 "/Users/user_name/workspace/runteq/PF/kinoko2/db/seeds/wise_saying.rb"]

となる。

●descメソッドは、直後のRakeタスクの説明を登録するため、 "Load the seed data from db/seeds/#{File.basename(file)}."がtaskの説明文として登録される。

$ bundle exec rake -D
...
rake db:seed:result
    Load the seed data from db/seeds/result.rb.

rake db:seed:wise_saying
    Load the seed data from db/seeds/wise_saying.rb.
...

●File.basename(filename)は、filename の一番後ろのスラッシュに続く要素を返す。

[12] pry(main)> Dir.glob(File.join(Rails.root, 'db', 'seeds', '*.rb')).each {|file| p "#{File.basename(file)}."}
"result.rb."
"wise_saying.rb."

正規表現を使ってdb/seeds下のファイル名の拡張子名を除外する。 メタ文字をリテラルのように、文字としてマッチさせるためには、\をつける。(メタ文字:( ) [ ] { } . ? + * | )

..:いずれかの1文字+:1回以上 (greedy)

$:行末にマッチする。行末とは文字列の末尾もしくは改行の手前を意味する。

/..+$/という正規表現は、デリミタの/(スラッシュ)で囲まれていて、/※の後にいずれかの文字が1つ以上ある、文字列を指している。※ /(スラッシュ)は(バックスラッシュ)でエスケープされている。

gsub(pattern, replace)は、文字列中でpatternにマッチする部分全てを文字列replaceで置き換えた文字列を生成して返すので、

pry(main)> Dir.glob(File.join(Rails.root, 'db', 'seeds', '*.rb')).each {|file| p "#{File.basename(file).gsub(/\..+$/, '')}"}
"result"
"wise_saying"

となり、"db:seed:#{File.basename(file).gsub(/..+$/, '')}"はdb:seed:resultとdb:seed:wise_sayingになり、taskが定義される。

●taskが実行されるとファイルが読み込まれるようにするために、load(file)でRubyのプログラムfileをロードして実行する。ロードするモジュールとしてはrequireもあるが、require はライブラリのロードに使用され、loadは設定ファイルの読み込みなどに使用される。

rakeタスクに反映されてるか確認

$ rake -h
...
→ -T, --tasks [PATTERN]
Display the tasks (matching optional PATTERN) with descriptions, then exit. -AT combination displays all of tasks contained no description.
...

(オプションのPATTERNに一致する)タスクを説明とともに表示し、終了する。
-ATコンビネーションでは、説明のないタスクをすべて表示します。
$ bundle exec rake -T
...
rake db:seed:result                     # Load the seed data from db/seeds/result.rb
rake db:seed:wise_saying                # Load the seed data from db/seeds/wise_saying.rb
...

参考文献

Railsでseedデータを分割して実行できるようにする - Passion make things more better

File.join (Ruby 3.0.0 リファレンスマニュアル)

Dir.[] (Ruby 3.0.0 リファレンスマニュアル)

File.basename (Ruby 3.0.0 リファレンスマニュアル)

Kernel#desc (Ruby 3.0.0 リファレンスマニュアル)

正規表現とは?メタ文字とサンプル一覧 | WWWクリエイターズ

Kernel.#load (Ruby 3.0.0 リファレンスマニュアル)

http://interfirm.hatenablog.com/entry/2014/05/30/195044

<Ruby on Rails > 開発環境で本番環境のようにerror画面を発生させる設定

忘れてたのでメモ

# config/development.rb

# Show full error reports.
config.consider_all_requests_local: false

true:デバッグ情報がHTTPレスポンスに出力され、コンテキストがRails::Infoコントローラによって/rails/info/propertiesに出力される。

develpmentとtestのdefault設定:true
productionのdefault設定:false

<Ruby on Rails エラー編> production環境でのrails sでActionController::RoutingErrorのエラーが発生

$ bundle exec rails s -e production

プロダクション環境でサーバーを立ち上げたところ、scssが反映されていなかった。
原因を調べるためにproduction.logを見たところ、以下のようなログになっていた。

I, [2021-06-08T22:49:53.332919 #8860]  INFO -- : [d81593ef-a63e-4d17-b96a-5aeced17da63] Started GET "/" for 127.0.0.1 at 2021-06-08 22:49:53 +0900
I, [2021-06-08T22:49:53.471239 #8860]  INFO -- : [d81593ef-a63e-4d17-b96a-5aeced17da63] Processing by TopController#index as HTML
I, [2021-06-08T22:49:53.534582 #8860]  INFO -- : [d81593ef-a63e-4d17-b96a-5aeced17da63]   Rendered top/index.html.slim within layouts/application (Duration: 40.9ms | Allocations: 19794)
I, [2021-06-08T22:49:53.603623 #8860]  INFO -- : [d81593ef-a63e-4d17-b96a-5aeced17da63] [Webpacker] Everything's up-to-date. Nothing to do
I, [2021-06-08T22:49:53.781214 #8860]  INFO -- : [d81593ef-a63e-4d17-b96a-5aeced17da63]   Rendered shared/_privacy_policy.html.slim (Duration: 174.0ms | Allocations: 21561)
I, [2021-06-08T22:49:53.803296 #8860]  INFO -- : [d81593ef-a63e-4d17-b96a-5aeced17da63]   Rendered shared/_terms_of_use.html.slim (Duration: 20.5ms | Allocations: 23845)
I, [2021-06-08T22:49:53.803536 #8860]  INFO -- : [d81593ef-a63e-4d17-b96a-5aeced17da63]   Rendered layout layouts/application.html.slim (Duration: 310.0ms | Allocations: 76746)
I, [2021-06-08T22:49:53.804010 #8860]  INFO -- : [d81593ef-a63e-4d17-b96a-5aeced17da63] Completed 200 OK in 333ms (Views: 318.3ms | Allocations: 78813)
I, [2021-06-08T22:49:53.917030 #8860]  INFO -- : [92858f66-6b92-4867-9074-0e4ce8ab7a25] Started GET "/packs/js/application-731e33cfa57f5ac52f87.js" for 127.0.0.1 at 2021-06-08 22:49:53 +0900
F, [2021-06-08T22:49:53.917811 #8860] FATAL -- : [92858f66-6b92-4867-9074-0e4ce8ab7a25]   
[92858f66-6b92-4867-9074-0e4ce8ab7a25] ActionController::RoutingError (No route matches [GET] "/packs/js/application-731e33cfa57f5ac52f87.js"):
[92858f66-6b92-4867-9074-0e4ce8ab7a25]   

/packs/js/~がActionController::RoutingErrorを起こしている。

対処法

public以下のpacksが読み込めていない。
config/environments/production.rbのconfig.public_file_server.enabledをtrueにすることで読み込むことができるようになる。

config.public_file_server.enabled:
public/ディレクトリ内の静的アセットを扱うかどうかを指定します。
デフォルトではtrueが設定されますが、production環境ではアプリケーションを実行するNginxやApacheなどのサーバーが静的アセットを扱う必要があるので、falseになります。
デフォルトの設定とは異なり、WEBrickをでアプリケーションをproductionモードで実行したり(WEBrickをproductionで使うことは推奨されません)テストしたりする場合はtrueに設定します。
そうしないとページキャッシュが利用できなくなり、public/ディレクトリ以下に常駐する静的ファイルへのリクエストも有効になりません。
Rails アプリケーションを設定する - Railsガイド