in Think

Ruby on Railsおさらい大会

すろっくさんだよ。

明後日くらいにはRubyの2.6がでるのでしょうか。来年春にはRailsも6がでるらしいですね。

この辺でRailsのおさらいをしていきましょう。変更点を追っかけても、どうつかわれている変更点がわからないとよくわからずに雰囲気で作ることになりますしね。

この記事はRailsアプリケーションの一歩目を作るまでをやります。VagrantやDockerでもいいんですけど、理解難しいです。そういうのはあとのほうでやります。

アプリケーションの名前は「musiclinks」となっています。

あとUnix系OSでの開発が捗るので。ここではmacOSでの作業をしていきます。デプロイ先はLinuxです。

以下を用意しました。

  • MacBookという名前のなにか
  • githubのアカウント
  • Vim

homebrewインストール

macOSでのパッケージ管理はhomebrewで。いれるときはこんな感じのがdotfileにあるので抜粋。


#!/bin/sh
BREW_ST=`which brew`
if [ $? -ne 0 ]; then
  ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)"
fi
export PATH=$PATH:/usr/local/bin
CURRENT_PATH=`pwd`
export HOMEBREW_CASK_OPTS="--appdir=/Applications"

実行。

$ sh brew_install.sh

準備

僕はrvmで大体やってます。一般ユーザで。


$ curl -sSL https://get.rvm.io | bash -s stable

rvmのインストール終わったらRubyいれる。


$ rvm install 2.5.3

MySQLいれる。5.6を狙って大体いれるけど、これで。


$ brew install mysql

起動。


$ mysql.server start

Railsいれるよ

それじゃここからRailsもろもろっすね。

アプリケーションの名前今回は「musiclink」というなんか音楽らしいものをいじるのを作ります。


$ mkdir musiclinks
$ cd musiclinks
$ gem install bundler
$ bundle init

次はRubyのバージョンと、gemset。


$ echo 2.5.3 > .ruby-version
$ echo musiclink > .ruby-gemset
$ cd .

アプリケーション直下にGemfileというファイルがあるので開いて、以下を書く。


frozen_string_literal: true
source "https://rubygems.org"
git_source(:github) {|repo_name| "https://github.com/#{repo_name}" }

gem “rails"

いれます。


$  bundle install

みんな大好きRailsプロジェクト開始!


$ rails new . -d mysql

途中で「.ruby_version上書きする?」って聞いてくるんですが、もう設定してあるのでnに。あとはyにして続行。

こんなファイル&ディレクトリがフォルダの下に作成かんりょ!


.git/
.gitignore
.ruby-gemset
.ruby-version
Gemfile
Gemfile.lock
README.md
Rakefile
app/
bin/
config/
config.ru
db/
lib/
log/
package.json
public/
storage/
test/
tmp/
vendor/

次はこのアプリケーションで使うDB。


$ rails db:create
Created database 'musiclinks_development'
Created database 'musiclinks_test'

これで準備OK。開発用のサーバを開きます。


rails s 
—————
=> Booting Puma
=> Rails 5.2.2 application starting in development
=> Run `rails server -h` for more startup options
Puma starting in single mode...
* Version 3.12.0 (ruby 2.5.3-p105), codename: Llamas in Pajamas
* Min threads: 5, max threads: 5
* Environment: development
* Listening on tcp://0.0.0.0:3000
Use Ctrl-C to stop
Started GET "/" for 127.0.0.1 at 2018-12-21 08:40:40 +0900

http://0.0.0.0:3000にアクセスして以下がでればOK

あとはgit登録。


$ git add . 
$ git commit “初回コミット”
$ git remote add origin git@github.com:srockstyle/musiclinks.git
$ git push origin musiclinks

ここまでは大体いつもなんかつくろっかなーと思ったらやってるので、かるいおさらいです。「Rails 始める」とかで検索すると大体でてくるあれです。

次回からこれに肉付けしていきます。

このアプリケーションのリポジトリは以下。

https://github.com/srockstyle/musiclinks