Rails 6 でTodoApp作る part1

Rails6を使って簡単なTodoAppを作っていきます。 後から自分で見て復習できるような感じで書いていきます。


環境 macローカル
Ruby 2.6.5
Rails 6.0.2.1
% rails new todo_app

% cd todo_app

% rails db:create
Created database 'db/development.sqlite3'
Created database 'db/test.sqlite3'

% rails s

f:id:yukitoku_sw:20200115210555p:plain

初期設定

slim化

Gemfileにgem 'slim-rails'gem 'html2slim'を追記する


[ Gemfile ]

source 'https://rubygems.org'
git_source(:github) { |repo| "https://github.com/#{repo}.git" }

ruby '2.6.5'

# Bundle edge Rails instead: gem 'rails', github: 'rails/rails'
gem 'rails', '~> 6.0.2', '>= 6.0.2.1'
# Use sqlite3 as the database for Active Record
gem 'sqlite3', '~> 1.4'
# Use Puma as the app server
gem 'puma', '~> 4.1'
# Use SCSS for stylesheets
gem 'sass-rails', '>= 6'
# Transpile app-like JavaScript. Read more: https://github.com/rails/webpacker
gem 'webpacker', '~> 4.0'
# Turbolinks makes navigating your web application faster. Read more: https://github.com/turbolinks/turbolinks
gem 'turbolinks', '~> 5'
# Build JSON APIs with ease. Read more: https://github.com/rails/jbuilder
gem 'jbuilder', '~> 2.7'
# Use Redis adapter to run Action Cable in production
# gem 'redis', '~> 4.0'
# Use Active Model has_secure_password
# gem 'bcrypt', '~> 3.1.7'

# Use Active Storage variant
# gem 'image_processing', '~> 1.2'

# Reduces boot times through caching; required in config/boot.rb
gem 'bootsnap', '>= 1.4.2', require: false

group :development, :test do
  # Call 'byebug' anywhere in the code to stop execution and get a debugger console
  gem 'byebug', platforms: [:mri, :mingw, :x64_mingw]
end

group :development do
  # Access an interactive console on exception pages or by calling 'console' anywhere in the code.
  gem 'web-console', '>= 3.3.0'
  gem 'listen', '>= 3.0.5', '< 3.2'
  # Spring speeds up development by keeping your application running in the background. Read more: https://github.com/rails/spring
  gem 'spring'
  gem 'spring-watcher-listen', '~> 2.0.0'
end

group :test do
  # Adds support for Capybara system testing and selenium driver
  gem 'capybara', '>= 2.15'
  gem 'selenium-webdriver'
  # Easy installation and use of web drivers to run system tests with browsers
  gem 'webdrivers'
end

# Windows does not include zoneinfo files, so bundle the tzinfo-data gem
gem 'tzinfo-data', platforms: [:mingw, :mswin, :x64_mingw, :jruby]

gem 'slim-rails' # 追加
gem 'html2slim' # 追加
% bundle

これでslim化されます。 しかし、rails newにより作成されたapp/views/layoutsの中身はerbのままなので、それらをslim化する

% bundle exec erb2slim app/views/layouts/ --delet

これでアプリのslim化が完了

Rails 6 + webpacker + Bootstrap

わかりやすかった↓記事から自分に必要な部分を真似させていただきました。

Rails 6+Webpacker開発環境をJS強者ががっつりセットアップしてみた(翻訳)|TechRacho(テックラッチョ)〜エンジニアの「?」を「!」に〜|BPS株式会社


Rails 6 ではwebpackerを使ってjavascriptを使うのが乙なようですよ。

今までは、app/assets/stylesheet/application.scssからBootstrapを読み込んでいたが、webpackerでは、`app/javascript/packから読み込む。

そのためにはapplication.html.slimを変更する必要があります。

変更前 = stylesheet_link_tag 'application', media: 'all', 'data-turbolinks-track': 'reload' 変更後 = stylesheet_pack_tag 'application', media: 'all', 'data-turbolinks-track': 'reload'

link を pack に変更し下記のようになります。


[ app/views/layouts/application.html.slim]

doctype html
html
  head
    title
      | TodoApp
    = csrf_meta_tags
    = csp_meta_tag
    = stylesheet_pack_tag 'application', media: 'all', 'data-turbolinks-track': 'reload'
    = javascript_pack_tag 'application', 'data-turbolinks-track': 'reload'
  body
     = yield

これにより、app/javascript/pack/application.jsを読み込むようになります。

しかし、jsファイルにcssを書くことはできないのでscssファイルを作成します。


[ app/javascript/src/style.scss ]

@import "~bootstrap/scss/bootstrap"; 

app/javascript/内であればフォルダ名・ファイル名はなんでもok。

そして、app/javascript/pack/application.jsにもimportします。


[ app/javascript/pack/application.js ]

// This file is automatically compiled by Webpack, along with any other files
// present in this directory. You're encouraged to place your actual application logic in
// a relevant structure within app/javascript and only use these pack files to reference
// that code so it'll be compiled.

require("@rails/ujs").start()
require("turbolinks").start()
require("@rails/activestorage").start()
require("channels")

// Uncomment to copy all static images under ../images to the output folder and reference
// them with the image_pack_tag helper in views (e.g <%= image_pack_tag 'rails.png' %>)
// or the `imagePath` JavaScript helper below.
//
// const images = require.context('../images', true)
// const imagePath = (name) => images(name, true)

import "../src/style" # 追加


やっとこさBootstrapのインストールです。

しかし、webpackerを使う場合はbundle installではなくyarnを使います。


[ コンソール ]

% yarn add bootstrap jquery popper.js

Bootstrapに必要な依存関係の奴らも一緒にインストール

インストールしたファイルをrequireします。


[ app/javascript/pack/application.js ]

// This file is automatically compiled by Webpack, along with any other files
// present in this directory. You're encouraged to place your actual application logic in
// a relevant structure within app/javascript and only use these pack files to reference
// that code so it'll be compiled.

require("@rails/ujs").start()
require("turbolinks").start()
require("@rails/activestorage").start()
require("channels")

require("jquery");   # 追加
require("bootstrap");  # 追加

// Uncomment to copy all static images under ../images to the output folder and reference
// them with the image_pack_tag helper in views (e.g <%= image_pack_tag 'rails.png' %>)
// or the `imagePath` JavaScript helper below.
//
// const images = require.context('../images', true)
// const imagePath = (name) => images(name, true)

import "../src/style"


Yarnの設定


[ コンソール ]

yarn policies set-version 1.21.1

1.21.1は私が使ったバージョンなので最新版を使った方が良いかと思います。

package.jsonnodeyarnを追加すると下記のようになります。


[ package.json ]

{
  "name": "todo_app",
  "private": true,
  "dependencies": {
    "@rails/actioncable": "^6.0.0",
    "@rails/activestorage": "^6.0.0",
    "@rails/ujs": "^6.0.0",
    "@rails/webpacker": "4.2.2",
    "bootstrap": "^4.4.1",
    "jquery": "^3.4.1",
    "popper.js": "^1.16.0",
    "turbolinks": "^5.2.0"
  },
  "version": "0.1.0",
  "devDependencies": {
    "webpack-dev-server": "^3.10.1"
  },
  "engines": {                     # 追加
    "node": "13.5.0",          # 追加
    "yarn": "1.21.1"             # 追加
  }
}

以上で、初期設定はおしまいです。

次回、Task作る