僕の世界観を変えてみる

文系男子が趣味でプログラミングを勉強していくブログです。他にも日常で起きたどうでもいいことや愚痴を書いていきたいです。座右の銘は和を以て貴しとなすです。仲良くやろうよ。

cloud9でrailsサーバを立ち上げる、の巻

$ rails s -b 0.0.0.0

cloud9ではipを0.0.0.0に指定する

f:id:htmllifehack:20200726123627p:plain

Specified 'sqlite3' for database adapter, but the gem is not loaded. Add gem 'sqlite3' to your Gemfile (and ensure its version is at the minimum req

sqlite3のバージョンを指定する必要がある。

rails newで作成したディレクトリ内にあるGemfileを編集する

$ vim Gemfile

>>
source 'https://rubygems.org'


# Bundle edge Rails instead: gem 'rails', github: 'rails/rails'
gem 'rails', '~> 5.0.0'
# Use sqlite3 as the database for Active Record
gem 'sqlite3', '~>1.3.6'

もう一度サーバを起動させてみる。

$ rails s -b 0.0.0.0

>>
Could not find gem 'sqlite3 (~> 1.3.6)' in any of the gem sources listed in your Gemfile.
Run `bundle install` to install missing gems.

bundle installするように言われているのでやってみる。

$ bundle install

>>
Bundle complete! 15 Gemfile dependencies, 62 gems now installed.
Use `bundle info [gemname]` to see where a bundled gem is installed.

一応updateもしておく。

$ bundle update

>>
Bundle updated!

再度サーバを起動。

$ rails s -b 0.0.0.0

f:id:htmllifehack:20200726124756p:plain

成功

【Ruby on Rails】rails --server でサーバが起動しない件について

ruby on rails で少し遊ぼうと思ったが最初からエラーの連発で大変だったのでまとめようと思う。

環境

  • Vagran Ubuntu/trasty64

  • Ruby -v 2.7.1

railsのインストール

$ gem install rails
$ rails -v
>>
6.0.3.2

railsはデフォルトのデータベースにsqlite3を使用するようなのでsqlite3もインストールする。

$ sudo apt install sqlite3
$ 

rails newを実行するとBuildErrorが発生

ドットインストールに倣いmy_appという名前でアプリを作成してみる。

$ rails new my_app

>>
Gem::Ext::BuildError: ERROR: Failed to build gem native extension.
An error occurred while installing sassc (2.4.0), and Bundler cannot continue.
Make sure that `gem install sassc -v '2.4.0' --source 'https://rubygems.org/'` succeeds before
bundling.
Could not find gem 'sqlite3 (~> 1.4)' in any of the gem sources listed in your Gemfile.
Run `bundle install` to install missing gems.

この時点でたくさんのエラーが表示されていた。

ドットインストールの補足にはGemfile内のsqlite3の記述部分を変更すると書かれていたが、大丈夫そうだったのでそのままにした。

bundle install

$ bundle install
>>
Gem::Ext::BuildError: ERROR: Failed to build gem native extension.
An error occurred while installing sassc (2.4.0), and Bundler cannot continue.
Make sure that `gem install sassc -v '2.4.0' --source 'https://rubygems.org/'` succeeds before
bundling.

sqlite3に関するエラーは消えたがBuildエラーは出ていたのでMake sure thatgem install sassc -v '2.4.0' --source 'https://rubygems.org/'succeeds beforeこの部分を試してみる。

gem install sassc -v '2.4.0' --source 'https://rubygems.org/'

bundlerの実行ができなかったので次のコマンドを試すように促されている。

$ gem install sassc -v '2.4.0' --source 'https://rubygems.org/'
>>
Building native extensions. This could take a while...
Successfully installed sassc-2.4.0
Parsing documentation for sassc-2.4.0
Installing ri documentation for sassc-2.4.0
Done installing documentation for sassc after 0 seconds
1 gem installed

コマンドはうまく行ったようで、sasscのインストールが完了したらしい。

sasscを調べても速いぞ!って記事しか見つからなかったのでなんなのかわからないがsassのコンパイラかなにかだろうか。

railsサーバを起動してみる

rails newで作成したmy_appディレクトリに移動してサーバを起動してみる。

rails sでサーバを起動、-bでipアドレスを指定、-dでバックグラウンドでサーバを起動させるオプション。

$ cd my_app
$ rails s -b 192.168.33.10 -d

>>
Could not find gem 'sqlite3 (~> 1.4)' in any of the gem sources listed in your Gemfile.
Run `bundle install` to install missing gems.

またもsqlite3bundle installしろと表示がでてきた。

bundle updateしてみる

bundle, Gemfileについて調べていたらこんなQiitaが出てきた。

Bundler, Gemfile, Gemfile.lock について - Qiita

すでに用意された Gem に変更を加える場合は Gemfile.lock を修正し、 bundle update を行います。例えばバージョンの変更や不必要な Gem を削除したい時などです。

とあったのでbundle updateしてみる。

$ bundle update
>>
Bundle updated!

bundle updateはうまくいったようなのでもう一度サーバを起動させてみる。

$ rails s -b 192.168.33.10 -d

>>
in `rescue in load': Webpacker configuration file not found /home/vagrant/workspace/ruby/rails_lessons/my_app/config/webpacker.yml. Please run rails webpacker:install Error: No such file or directory @ rb_sysopen - /home/vagrant/workspace/ruby/rails_lessons/my_app/config/webpacker.yml (RuntimeError)  

ずらずらと文字が出てきて最終的にrails webpacker:installするように促された。

rails webpacker:installしてみる

$ rails webpacker:install

>>
sh: 1: node: not found
sh: 1: nodejs: not found
Node.js not installed. Please download and install Node.js https://nodejs.org/en/download/

と、nodeがないからインストールするように言われる。

nodeとnodejsと一応npmをインストールする
$ sudo apt-get install nodejs npm node
$ rails webpacker:install
>>
Webpacker requires Node.js >= 8.16.0 and you are using 0.10.25
Please upgrade Node.js https://nodejs.org/en/download/

(え、nodeとnodejsの違いがわからない…)

一通りエラーもなくインストールできたのであらためてrails webpackerをインストールしてみると今度はNode.jsのバージョンをあげるように言われた。

nodejsのアップデート

nodejs ubuntu アップデートで検索したところnと呼ばれるパッケージを使ってアップデートできると記事があったので試してみる。

$ sudo npm install n -g
>>
npm ERR! If you need help, you may report this log at:
npm ERR!     <http://github.com/isaacs/npm/issues>

npmのエラーが連発していて、今度はgithubのissuesを見るように促されたのでアクセスしてみる。

インストールについてnpm ERR! Error: ENOENT, open ~ /gulp/package.json · Issue #2 · inc2734/mimizuku-child · GitHub

どうやらnodeとnpmのバージョンが古いことが原因らしい。

node -v v0.10.25 npm -v 1.3.10

激古

ということなのでいったんnpmのバージョンアップをしてnodeのバージョンアップを試みる。

npm update -g npm してみる

npmを使ってnpm自身をアップデートできるらしい。

$ npm update -g npm

さて、このコマンドを実行しても反応がない。

npm -vしてみてもバージョンアップは1.3.10のまま。

と、ここでふと思ったのがアップデートする順番ってnode.jsが先じゃない?

nvmでNode.jsのバージョン管理

githubのissuesにあったようにnvmを使ってnodeのバージョンアップをしてみる。

※あとで知ったけどバージョン管理はnvmのほかにnodenvnodist, nなどあるらしい。

$ curl -o- https://raw.githubusercontent.com/creationix/nvm/master/install.sh | bash

これでnvmのインストールができた。

sourceコマンドでbashrcディレクトリを更新してnvmのバージョンを確認してみる。

$ source ~/.bashrc
$ nvm --version

>>
0.35.2

次にnodeのバージョンを上げる

nvm ls-remoteコマンドでnodeのバージョン一覧を確認できるが、もう安定板でいい。

$ nvm install stable


>>
Now using node v14.6.0 (npm v6.14.6)
Creating default alias: default -> stable (-> v14.6.0)

nodeのバージョンアップをしたことでnpmもバージョンアップできたっぽい。

yarnをインストールする

npmのバージョンアップができたのでwebpackerのインストールをもう一度試みる。

$ rails webpacker:install
>>
Yarn not installed. Please download and install Yarn from https://yarnpkg.com/lang/en/docs/install/

すると今度はyarnをインストールするように言われた。

yarnとはnpmと同様パッケージマネージャーらしい。 ▼パッケージマネージャとは

$ sudo apt install yarn
>>
Reading package lists... Done
Building dependency tree       
Reading state information... Done
E: Unable to locate package yarn

むむ、apt曰くyarnが見つからないらしいのでyarnの公式を見てみる。

Installation | Yarn

どうやらリポジトリの設定をしてからでないとインストールできないようだ。

公式サイトにあるようにコマンドを実行していく。

$ curl -sS https://dl.yarnpkg.com
/debian/pubkey.gpg | sudo apt-key add -

>>OK
$ echo "deb https://dl.yarnpkg.co
m/debian/ stable main" | sudo tee /etc/apt/sources.list.d/yarn.list

>>deb https://dl.yarnpkg.com/debian/ stable main

リポジトリの設定が終わったのでyarnをインストールをしていく。

$ sudo apt update && sudo apt install yarn

>>Setting up yarn (1.22.4-1) ...

yarnのインストールも終わったようだ。

rails webpacker:installを再度試す

rails webpacker:installに戻る。

$ rails webpacker:install

>>
run  yarn add --dev webpack-dev-server from "."
info No lockfile found.
An unexpected error occurred: "EPROTO: protocol error, symlink...
Webpacker successfully installed �🎉

webpackerのインストールは成功。

しかし、yarnのほうでエラーがでていた。

このままサーバを起動してみてもうまくいくが、yarnのエラーが気になるので直そう。

yarn add --dev webpack-dev-serverを追加するようにと、yarnのlockfileがないのと、symlinkで予期せぬエラーが発生したということ。

symlinkはホストOSとゲストOSとのファイル共有のことらしいのでrootに移動してから(今はrails newで作成したmy_appディレクトリにいるので)yarn add --dev webpack-dev-serverコマンドを試してみる。

$ yarn add --dev webpack-dev-server`

>>
success Saved lockfile.
success Saved 253 new dependencies.
.
.
.
Done in 3.87s.

いくつかwarningはでているがうまく行ったらしい。

railsサーバを起動してみる

$ $ rails s -b 192.168.33.10 -d   

>>
=> Booting Puma
=> Rails 6.0.3.2 application starting in development
=> Run `rails server --help` for more startup options

エラーもでないので192.168.33.10:3000にアクセスしてみる。

f:id:htmllifehack:20200726033306p:plain
rails server

まとめ

環境構築が一番大変。

Ruby初心者がrbenvを使ってRubyのバージョンアップを試みる

環境 ツール : vagrant OS : Ubuntu-trusty-64

問題

rubyのバージョンを確認したところ1.9.3となっていた(2020年7月の最新は2.8.0)

$ ruby -v

>>
ruby 1.9.3p484 (2013-11-22 revision 43786) [x86_64-linux]

あまりに古いのでrubyのバージョンアップを試してみる。

rbenvで最新のRubyのバージョンが表示されない件

バージョン管理のためにrbenvでインストール。

$ rbenv install -l

>>
Available versions:
  1.8.6-p383
   ~
  1.9.3-preview1
  1.9.3-rc1
  2.0.0-dev

すると、2.0.0までしか表示されなかった。

ググってみると先人たちが解決方法を記載していてくれた。

Ruby 2.3.0がrbenvに表示されない時にやったこと - Qiita

rbenvでRubyのバージョンアップをする(for Mac) - Qiita

rbenv, ruby-buildをアップグレード

まずはrbenvruby-buildをアップグレードするようだ。

$ apt-gent upgrade rbenv ruby-build

>>
rbenv is already the newest version.
ruby-build is already the newest version.

二つとも最新になっているようだ。

しかし、rbenv install -lをしても2.0.0しか表示されない。

では次の方法。

rbenvをGit pullする

次はGitから最新のrbenvpull`してみる。

rbenv/plugins/ruby-build: No such file or directory問題
$ cd ~/.rbenv/plugins/ruby-build

>>
bash: cd: /root/.rbenv/plugins/ruby-build: No such file or directory

むむ。

ディレクトリが見つからないらしい。

ルートの隠しファイルを見ても見つからない。

そもそも.rbenv自体がない。

alreadyと表示されていたのになぜだ。

試しにwhichしてみる。

$ which rbenv

>>
/usr/bin/rbenv

うむ、rbenvは存在するけれどもrootにいない?

これは…pathの問題だろうか?

rbenvを入れなおす

apt-get updateしても改善されなかったので下記のQiitaを参考にrbenvをgit cloneしてみる。

CentOSにrbenv, Rubyをインストールする - Qiita

$ git clone https://github.com/sstephenson/rbenv.git ~/.rbenv

ルートディレクトリに.rbenvを作成しその中にcloneするようだ。

自分でrootに.rbenvを作らなければいけなかったのか。

$ ls -d ~/.rbenv

>>
/root/.rbenv

中身を確認しても~/.rbenv/plugins/ruby-buildのようなディレクトリは存在しなかった。

これも自分で作成するようなのでruby-buildgit cloneする。

$ git clone https://github.com/sstephenson/ruby-build.git ~/.rbenv/plugins/ruby-build

これで.rbenvpluginのディレクトリが作成され、準備が整った。

作成した/.rbenv/plugins/ruby-buildに移動しgit pullしてみる。

$ cd ~/.rbenv/plugins/ruby-build
$ git pull

Already up-to-date.と表示されたらrbenvのアップデート完了

rbenv install -lをしてみるとたくさんのバージョンが確認できる。

>>
Available versions:
  1.8.5-p52
 ~
  2.7.1
  2.8.0-dev

rbenv installするとruby-buildのヘルプが表示される件

これでRubyのバージョンを上げられると思いインストールを試すと

$ rbenv install 2.7.1
Usage: ruby-build [-kpv] <definition> <prefix>
       ruby-build --definitions
       ruby-build --version

  -k/--keep        Do not remove source tree after installation
  -p/--patch       Apply a patch from stdin before building
  -v/--verbose     Verbose mode: print compilation status to stdout
  -4/--ipv4        Resolve names to IPv4 addresses only
  -6/--ipv6        Resolve names to IPv6 addresses only
  --definitions    List all local definitions
  -l/--list        List latest stable releases for each Ruby
  --version        Show version of ruby-build

このようにruby-buildの使い方が表示された。

ということでさらにググり続けたところrbenvはパスを通してから初期化をしないと使えないという記事を見かけた。

rbenvとruby環境の構築手順

上記の記事に書かれていることがすべてだ。

rbenvのPathを通す

まずはrbenvが使えるようにパスを通す。

$ echo 'export PATH="$HOME/.rbenv/bin:$PATH"' >> ~/.bashrc

rbenv を初期化する。

次に/.rbenv/binに移動し、初期化する。

$ cd ~/.rbenv/bin
$ rbenv init

>>
# Load rbenv automatically by adding
# the following to ~/.bash_profile:

eval "$(rbenv init -)"

eval "$(rbenv init -)"これをするようにと表示されたのでやってみる。

※最終的に上記のコマンドだとうまく行きませんでした。 記事の最後に追記してあります。

$ eval "$(rbenv init -)"

特別なにも表示されなかったがエラーもでなかったので成功したようだ。

.bashrcを再読み込みしてからもう一度Rubyのバージョンリストを確認してみる。

$ source ~./bashrc
$ rbenv install -l

>>
2.5.8
2.6.6
2.7.1
jruby-9.2.12.0
maglev-1.0.0
mruby-2.1.1
rbx-5.0
truffleruby-20.1.0
truffleruby+graalvm-20.1.0

Only latest stable releases for each Ruby implementation are shown.
Use 'rbenv install --list-all' to show all local versions.

すると最新バージョンのみが表示されるようになった。

欲しかったのは2.7.1なのでインストールしてみる。

$ rbenv install 2.7.1

>>
Downloading ruby-2.7.1.tar.bz2...
-> https://cache.ruby-lang.org/pub/ruby/2.7/ruby-2.7.1.tar.bz2
Installing ruby-2.7.1...
Installed ruby-2.7.1 to /home/vagrant/.rbenv/versions/2.7.1

できたっぽいぞ。

$ rbenv versions
* system
  2.7.1

2.7.1がいる!

globalを使って常に2.7.1を使用できるように指定する。

$ rbenv global 2.7.1
$ rbenv versions

>>
  system
* 2.7.1 (set by /home/vagrant/.rbenv/version)

vagrantからログアウトするとRubyのバージョンがもとに戻る件

このあとRubyのバージョンを確認したら2.7.1になっていたので満足してvagrantからログアウトした。

そして作業を再開しようとvagrantで接続したところ、Rubyのバージョンが1.9.3に戻っていた。

OMG

もう一度この方の記事を読んでみる。 ▼rbenvとruby環境の構築手順

すると、どうやら僕がやった'eval "$(rbenv init -)"'の部分が間違っていたようだ。

$ echo 'eval "$(rbenv init -)"' >> ~/.bashrc

~/.bashrcに 'eval "$(rbenv init -)"`を書き込む必要があった。

そしてもう一度~/.bashrcを再読み込みし、確認のため上記の記事にあったrbenv-doctorを試してみる。

$ curl -fsSL https://github.com/rbenv/rbenv-installer/raw/master/bin/ 
rbenv-doctor | bash
Checking for `rbenv' in PATH: multiple
  You seem to have multiple rbenv installs in the following locations.
  Please pick just one installation and remove the others.

  /home/vagrant/.rbenv/bin/rbenv
  /home/vagrant/.rbenv/bin/rbenv
  /home/vagrant/.rbenv/bin/rbenv
  /usr/bin/rbenv

Checking for rbenv shims in PATH: OK
Checking `rbenv install' support: /home/vagrant/.rbenv/plugins/ruby-build/bin/rbenv-install (ruby-build 
20200722)
Counting installed Ruby versions: 1 versions
Checking RubyGems settings: OK
Auditing installed plugins: OK

すべてOKになっているので大丈夫のようだ。

最後に設定を保存しなければいけない。

$ rbenv rehash

これでvagrantからログアウトし、再度ログインしてもRubyのバージョンが2.7.1に維持されるようになった。

めでたしめでたし。

vagrantインストール

windowsやmacOSが起動している状態で仮想的に他のOSを起動させることができるソフトがあります。

たとえばwindows10がインストールされたパソコン(ホストOS)上で仮想化ソフトを起動させLinuxOS(ゲストOS)を使うことができる、といったものです。

いわゆるエミュレータです。

代表的な仮想化ソフトとしてVirtualBox、VMwareが挙げられます。

何に使うのかというと、怪しいソフトを起動させるときなどに使用したり、ウイルスっぽいものを実行したり、

だいたいプログラムを実行させるときに使ったりします。

仮想マシン内であれば、ファイルが削除されたりOSが破壊されても痛手を負わなくて済みます。

また、ホストOSを汚すことなくさまざまなソフトをインストールしたり、実行したりできます。

最初はVirtualBoxなどを起動させるのでもいいのですが、徐々にマウスでの操作が億劫になってくる時期がきます。

VirtualBoxを起動させて、新規→簡単な設定→OS読み込み→初期設定→アップデート→etc...

そう、だるいんです。

Vagrant(ベイグラント)とは仮想環境の設定・構築をいくつかのコマンドで自動的にしてくれるとっても便利なソフトです。

これを使えばたとえ環境がぶっこわれてもすぐに元に戻すことができます。

またエンジニア界隈では開発環境と本番環境の誤差をなくすために仮想環境を使用したりします。

そのため、VagrantやDocker(後述するかもしれないししないかもしれない)といった環境構築を自動化させるソフトの操作は必須と言えます。

Vagrantインストール

※コマンドはすべてpowershellで入力しています。コマンドプロンプトでもできますがコマンドが異なる場合があるので注意してください。

https://www.vagrantup.com/downloads.htmlここからVagrantをダウンロードします。 64bit版をインストールしました。

次へと進んで行くだけです。

次にhttps://www.virtualbox.org/wiki/DownloadsここからVirtualBoxをダウンロードします。

windows hostsからexeをダウンロードし、インストールです。

> vagrant -v

上記のコマンドを実行してバージョンが表示されたら成功です。

Vagrant CloudからOSを取得しインストールする

Vagrant Cloud https://app.vagrantup.com/boxes/searchのページからUbuntuやCentOSなど好きなOSをインストールすることができます。

今回はubuntu/trusty64をインストールしていきたいと思います。

ubuntu/trusty64と書かれた部分をクリックします。

ページが切り替わったらあと、NewタブをクリックするとUbuntuをインストールするためのコマンドが表示されます。

f:id:htmllifehack:20200709001052p:plain
vagrant

Vagrant用のフォルダを作成して、その中で実行します。

$ mkdir Vagrant
$ cd Vagrant
$ vagrant init ubuntu/trusty64

初回はubuntuのインストールで時間がかかりますが簡単に環境構築ができます。

> 結果
A `Vagrantfile` has been placed in this directory. You are now
ready to `vagrant up` your first virtual environment! Please read
the comments in the Vagrantfile as well as documentation on
`vagrantup.com` for more information on using Vagrant.

と出力されたら完了です。

initとはinitializeの略で初期化するという意味なります。pythonなどのプログラミング言語でも登場する言葉です。

vagrant init でエラーがでたとき

今のVagrantはinitするだけで設定が終わりますが、以前まではvagrant box addというコマンドを使用する必要があったそうです。

が、Windows10でVagrant initをした際は特にエラーもでず vagrant upすることができましたが、MacでVagrant initした際はエラーがでました。

エラーの内容は忘れましたがVagrant cloudからBoxを追加してくれ的な言い回しだったと思います。

なのでもしもvagrant init Box名でうまく行かなかったときは

$ vagrant box add https://vagrantcloud.com/ubuntu/trusty64

としてください。

そのあとにvagrant init ubuntu/trusty64を実行するとうまく行くと思います。

vagrant 起動

初期化ができたのでVagrantを起動させてみます。

$ vagrant up

> 結果
 flag to force provisioning. Provisioners marked to run always will still run.

こんな感じの文言がでてきたら起動されています。

そして気が付けばvagrant initしたフォルダ内にVagrantfileが作成されているはずです。

次はこのVagrantfileにVagrantの設定を記述していきます。

vagrantfileの編集

# -*- mode: ruby -*-
# vi: set ft=ruby :

# All Vagrant configuration is done below. The "2" in Vagrant.configure
# configures the configuration version (we support older styles for
# backwards compatibility). Please don't change it unless you know what
# you're doing.
Vagrant.configure("2") do |config|
  # The most common configuration options are documented and commented below.
  # For a complete reference, please see the online documentation at
  # https://docs.vagrantup.com.

  # Every Vagrant development environment requires a box. You can search for
  # boxes at https://vagrantcloud.com/search.
  config.vm.box = "ubuntu/trusty64"

  # Disable automatic box update checking. If you disable this, then
  # boxes will only be checked for updates when the user runs
  # `vagrant box outdated`. This is not recommended.
  # config.vm.box_check_update = false

  # Create a forwarded port mapping which allows access to a specific port
  # within the machine from a port on the host machine. In the example below,
  # accessing "localhost:8080" will access port 80 on the guest machine.
  # NOTE: This will enable public access to the opened port
  # config.vm.network "forwarded_port", guest: 80, host: 8080

  # Create a forwarded port mapping which allows access to a specific port
  # within the machine from a port on the host machine and only allow access
  # via 127.0.0.1 to disable public access
  # config.vm.network "forwarded_port", guest: 80, host: 8080, host_ip: "127.0.0.1"

  # Create a private network, which allows host-only access to the machine
  # using a specific IP.
  config.vm.network "private_network", ip: "192.168.33.10"

  # Create a public network, which generally matched to bridged network.
  # Bridged networks make the machine appear as another physical device on
  # your network.
  # config.vm.network "public_network"

  # Share an additional folder to the guest VM. The first argument is
  # the path on the host to the actual folder. The second argument is
  # the path on the guest to mount the folder. And the optional third
  # argument is a set of non-required options.
  config.vm.synced_folder "./workspace", "/home/vagrant/workspace"

  # Provider-specific configuration so you can fine-tune various
  # backing providers for Vagrant. These expose provider-specific options.
  # Example for VirtualBox:
  #
  # config.vm.provider "virtualbox" do |vb|
  #   # Display the VirtualBox GUI when booting the machine
  #   vb.gui = true
  #
  #   # Customize the amount of memory on the VM:
  #   vb.memory = "1024"
  # end
  #
  # View the documentation for the provider you are using for more
  # information on available options.

  # Enable provisioning with a shell script. Additional provisioners such as
  # Ansible, Chef, Docker, Puppet and Salt are also available. Please see the
  # documentation for more information about their specific syntax and use.
  # config.vm.provision "shell", inline: <<-SHELL
  #   apt-get update
  #   apt-get install -y apache2
  # SHELL
end

Vagrantfileを開くとこんな感じになっていると思います。

いくつかコメントアウトを外してください。

たとえばconfig.vm.network "private_network", ip: "192.168.33.10"はVagrant上でネットワークに接続するさいに必要な設定です。

先頭の#を消してコードを有効にします。

ホストOSとゲストOSでファイル共有する

ホストOSとゲストOS間でファイル共有ができないと不便です。

VirutualBoxをGUI操作した方ならわかると思いますが、仮想化ソフトにはファイル共有機能が備わっています。

VagrantではVagrantfileに共有したいファイル名を記述し、Vagrantのプラグインをインストールすることでファイル共有ができます。

Vagrantfile内の ‘config.vm.synced_folder "../data", "/vagrant_data"`の部分が共有するファイルの記述です。

.../dataがホストOS、/vagrant_dataがゲストOS側です。

僕はC:\users\owner\document\vagrantvagrantfileが形成されているのでvagrantfileと同じ階層にworkspaceという名前のフォルダを作成しました。

なので../dataの部分を./workspaceに書き換えます。

次にVagrant側ですが、まずはVagrantに接続してフォルダを作成しましょう。

Vagrantの接続はvagrant sshで行います。

$ vagrant ssh

vagrant@vagrant-ubuntu-trusty-64:~$に切り替われば接続OKです。

Vagrantに接続後、僕はルートディレクトリにworkspaceという名前のフォルダを作成しました。

vagrant@vagrant-ubuntu-trusty-64:~$ mkdir workspace

なので、/vagrant_data/home/vagrant/workspaceに書き換えます。

これだけではファイル共有されないのでプラグインのインストールを行います。

Vagrantから抜け出すにはexitと入力します。

vagrant@vagrant-ubuntu-trusty-64:~$ exit

これでpowershellに戻ってきました。

powershellで下記のコマンドを実行します。

$ vagrant plugin install vagrant-vbguest

> 結果
Installing the 'vagrant-vbguest' plugin. This can take a few minutes...
Fetching micromachine-3.0.0.gem
Fetching vagrant-vbguest-0.24.0.gem
Installed the plugin 'vagrant-vbguest (0.24.0)'!

インストールが終わったらVagrantを再起動します。

Vagrantの再起動にはvagrant reloadコマンドを使います。

$ vagrant reload

> 結果
==> default: Mounting shared folders...
    default: /vagrant => C:/Users/owner/Documents/vagrant
    default: /home/vagrant/workspace => C:/Users/owner/Documents/vagrant/workspace

再起動させると最後のほうに上記のような文言が表示されていると思います。

これでファイル共有の設定ができたはずです。

ためしにvagrantに接続して適当なファイルを作成してみます。

vagrant@vagrant-ubuntu-trusty-64:~$ touch test.txt

Vagrant側でtest.txtというテキストファイルを作成しました。

ホスト側のエクスプローラーでC:\users\owner\document\vagrant\workspaceにアクセスするとtest.txt`の存在が確認できました。

これでファイル共有の設定は終了です。

Vagrantで使うコマンド

Vagrant環境を作るための初期化

$ vagrant init {Box名}

Vagrant起動

$ vagrant up

Vagrantから抜け出す

vagrant@vagrant-ubuntu-trusty-64:~$ exit

Vagrant停止

$ vagrant halt

Vagrant再起動

$ vagrant reload

Vagrant設定の削除

$ vagrant destroy

まとめ

Vagrant上でGo言語をインストールしようと試みたところCould not resolve 'archive.ubuntu.com'というエラーが表示されました。

エラーの最後にUnable to fetch some archives, maybe run apt-get update or try with --fix-missing?と表示されていたのでsudo apt-get updateをかけたのですが、同じようにCould not resolve 'archive.ubuntu.com'と出ました。

むむ、とググってみたところパッケージの初期化や仮想マシンのDNSを変更するといった記事をみつけたので、Vagrantfileを開いてみたらIPアドレスがコメントアウトされていたのに気づきました。

まあ、意外と簡単なところでつまずくんですよね笑

Goも無事インストールできたのでさっそくさわってみます!

そして学習が進んで行ったらVagrantにapacheを入れてサーバを立てようと思います!

それではごきげんよう。

参考にさせていただいた記事一覧

Vagrant ファイル共有 決定版 - Qiita

【まとめ】Vagrant コマンド一覧 - Qiita

・いちばん参考にしていたQiitaの記事を見失いました...

claspでGASのバージョン管理をする【Mac】

nodebrew install

% brew install nodebrew

Error: The following directories are not writable by your use

error

Error: The following directories are not writable by your user:

/usr/local/share/man/man8

You should change the ownership of these directories to your user.

% sudo chown -R $(whoami) /usr/local/share/man/man8

And make sure that your user has write permission.

%  chmod u+w /usr/local/share/man/man8

※nodebrewとはnode.jsのバージョン管理ツール

f:id:htmllifehack:20200625221647p:plain
node.js

バージョンをターミナルで変更できる。

chownはディレクトリの所有権の変更を行うコマンド -Rchownのオプション、下層のディレクトリもまとめて所有権を変更する。 $(whoami)whoamiの現在のユーザー名を表示、を変数化?

% nodebrew -v

>> 出力結果
nodebrew 1.0.1

node.js install

node.js のバージョン確認

% nodebrew ls-remote

>> 出力結果
v0.0.1    v0.0.2    v0.0.3    v0.0.4    v0.0.5    v0.0.6
.
.
.
v14.0.0   v14.1.0   v14.2.0   v14.3.0   v14.4.0 

nodebrew ls-remoteでnode.jsのバージョン一覧を確認できる。

% nodebrew install-binary stable
or
% nodebrew install-binary latest

install-binary stableで推奨版(現在は12.18.1)、install-binary latestで最新版(14.4.0)がインストールできる。

Warning: No such file or directory

error Fetching: https://nodejs.org/dist/v14.4.0/node-v14.4.0-darwin-x64.tar.gz Warning: Failed to create the file Warning: /Users/***/.nodebrew/src/v14.4.0/node-v14.4.0-darwin-x64.tar.gz: Warning: No such file or directory 0.0% curl: (23) Failed writing body (0 != 980) download failed: https://nodejs.org/dist/v14.4.0/node-v14.4.0-darwin-x64.tar.gz

4行目のWarningがエラー内容です。

ファイルかディレクトリがありませんとなっています。

なんのファイル、ディレクトリがないのかは3行目のWarningの.nodebrew/src/です。

nodebrewのソースファイル(.がついているので隠しファイル)がないのでこれを作成する必要があるみたいです。

% mkdir -p ~/.nodebrew/src

mkdir -pでフォルダがなければ作成すると言う意味です。

その後もう一度

% nodebrew install-binary stable
or
% nodebrew install-binary latest

でインストールされるはずです。

 % nodebrew install-binary latest

>> 実行結果
Fetching: https://nodejs.org/dist/v14.4.0/node-v14.4.0-darwin-x64.tar.gz
###############################################  100.0%
Installed successfully

node.jsを有効化

% nodebrew ls

>> 出力結果
v14.4.0

current: none

use バージョンでnode.jsを有効化。

% nodebrew use v14.4.0 
use v14.4.0

Pathを通す

echo 'export PATH=$HOME/.nodebrew/current/bin:$PATH' >> ~/.zprofile

参考にさせていただいたサイト qiita.com

clasp install

% npm install -g @google/clasp

https://script.google.com/home/usersettingsにアクセスし、APIをオンにする。

% clasp login

claspにログインするとブラウザが立ち上がり、Googleアカウントでログインすると設定は完了。

GASをcloneする

すでにGASを作成済みだったので、いったんローカルファイルにcloneする。

% mkdir GAS
% cd GAS
% clasp clone GASのスクリプトID

>> 実行結果
Warning: files in subfolder are not accounted for unless you set a '.claspignore' file.
Cloned 3 files.
└─ test.js
└─ コード.js
└─ appsscript.json
Not ignored files:
└─ appsscript.json
└─ test.js
└─ コード.js

Ignored files:
└─ .clasp.json

GASからファイル→プロジェクトのプロパティ→スクリプトIDの順で辿るとIDがわかります。

ローカルで編集したコードをGASに反映させる

% clasp push

Gitと同様pushであげることができます。

ただし、ファイルを指定することはできずフォルダ内の全てのファイルをアップする形になります。

ローカルからプロジェクトを新規作成

claspはcreateでプロジェクトを新規作成できます。

% clasp create ファイル名

% clasp create test_code
? Create which script? (Use arrow keys)
❯ standalone 
  docs 
  sheets 
  slides 
  forms 
  webapp 
  api 

GASを作る場合はstandaloneを選択します。

他はドキュメントやスプレッドシート、スライダーなどおなじみのGoogleサービスを作成する場合はいずれかを選択することができます。

error

Nested clasp projects are not supported.

僕は上記のようなエラーが発生しました。

ホームディレクトリ内に.claps.jsonファイルが存在していると出るエラーのようです。

【Google Apps Script】claspを使ってローカル環境で開発する - こぶろぐ。

createを行う前にcloneをしていたため一つ上のフォルダに.clasp.jsonがありました。

.clasp.jsonは隠しファイルです。

% ls -a

-aでオプションを追加してlsすると隠しファイルも表示されます。

finder上ではcommand + shift + .で表示非表示を切り替えられます。

.clasp.jsonの中身はGASのスクリプトIDが記載されていました。

.clasp.jsonを削除すればcreateできるようになるはずです。