LoginSignup
8
7

More than 5 years have passed since last update.

いまさらruby on rails 5 with VirtualBox on MAC

Last updated at Posted at 2016-08-03

こちらで作成したVM上にruby環境を構築していきます。

1. インストール

参考1, 参考2
参考を見ながら進めます。rubyの前提知識がないのでひたすらloggingしていきます。
最低限と思われるツール類をインストールしておきます。

[root@localhost admin]# yum groupinstall "Development Tools"
[root@localhost admin]# yum install gcc gcc-c++
[root@localhost admin]# yum install mlocate openssl-devel zlib-devel bzip2 bzip2-devel readline-devel sqlite3 sqlite-devel openssl-devel
..........
完了しました!

1.1 anyenvのインストール

[admin@localhost ~]$ git clone https://github.com/riywo/anyenv ~/.anyenv
Cloning into '/home/admin/.anyenv'...
remote: Counting objects: 238, done.
remote: Total 238 (delta 0), reused 0 (delta 0), pack-reused 238
Receiving objects: 100% (238/238), 36.64 KiB | 0 bytes/s, done.
Resolving deltas: 100% (89/89), done.
[admin@localhost ~]$ echo 'export PATH="$HOME/.anyenv/bin:$PATH"' >> .bash_profile
[admin@localhost ~]$ echo 'eval "$(anyenv init -)"' >> .bash_profile
[admin@localhost ~]$ exec $SHELL -l
[admin@localhost ~]$ anyenv --help
anyenv
Usage: anyenv <command> [<args>]

Some useful anyenv commands are:
   commands            List all available anyenv commands
   local               Show the local application-specific Any version
..........
Install rbenv succeeded!
Please reload your profile (exec $SHELL -l) or open a new session.

1.2 rvenvのインストール

[admin@localhost ~]$ anyenv install rbenv
/tmp/rbenv.20160803012838.4435 ~
Cloning https://github.com/rbenv/rbenv.git...
Cloning into 'rbenv'...
........
Install rbenv succeeded!
Please reload your profile (exec $SHELL -l) or open a new session.

[admin@localhost ~]$ exec $SHELL -l
[admin@localhost ~]$ rbenv install 2.3.0
Downloading ruby-2.3.0.tar.bz2...
-> https://cache.ruby-lang.org/pub/ruby/2.3/ruby-2.3.0.tar.bz2
Installing ruby-2.3.0...
Installed ruby-2.3.0 to /home/admin/.anyenv/envs/rbenv/versions/2.3.0

[admin@localhost system]$ rbenv global 2.3.0
[admin@localhost system]$ rbenv versions
* 2.3.0 (set by /home/admin/.anyenv/envs/rbenv/version)

1.3 MVCプロジェクト生成

  1. rbenv local 2.3.0で対象のディレクトリ内で利用するrbenvのバージョンを設定します。 コマンド実行後.ruby-versionが生成されます。
  2. bundler initでGemfileが生成されます。この中に必要なモジュールを記載していきます。
  3. bundle install --path vendor/bundleで依存関係のライブラリがインストールされます。
  4. bundle exec rails new my1stRails --skip-springでmy1stRailsというプロジェクトの雛形が出来上がります。
  5. my1stRailsに移動後、再度bundle install --path vendor/bundleをして依存関係のライブラリをインストール
  6. bundle exec rails serverで起動
  7. 6でコケたのでgem 'therubyracer'を追加して再度5を実行
  8. 6を再実行した後、tcp://localhost:3000で無事起動
[admin@localhost share]$ mkdir HelloRuby
[admin@localhost share]$ cd HelloRuby
[admin@localhost HelloRuby]$ rbenv local 2.3.0
[admin@localhost HelloRuby]$ ls -al
......
-rw-r--r-- 1 admin admin   6  8月  3 13:48 .ruby-version
[admin@localhost HelloRuby]$ gem install bundler
Fetching: bundler-1.12.5.gem (100%)
......
1 gem installed
[admin@localhost HelloRuby]$ bundler init
Writing new Gemfile to /home/admin/share/HelloRuby/Gemfile

[admin@localhost HelloRuby]$ vi Gemfile
# frozen_string_literal: true
# A sample Gemfile
source "https://rubygems.org"

gem "rails","5.0.0"

[admin@localhost HelloRuby]$ bundle install --path vendor/bundle
Fetching gem metadata from https://rubygems.org/...........
.............
Installing rails 5.0.0
Bundle complete! 1 Gemfile dependency, 39 gems now installed.
Bundled gems are installed into ./vendor/bundle.

[admin@localhost HelloRuby]$ ls -al
合計 12
drwxr-xr-x 1 admin admin  238  8月  3 13:56 .
drwxr-xr-x 1 admin admin  102  8月  3 13:47 ..
drwxr-xr-x 1 admin admin  102  8月  3 13:52 .bundle
-rw-r--r-- 1 admin admin    6  8月  3 13:48 .ruby-version
-rw-r--r-- 1 admin admin  100  8月  3 13:50 Gemfile
-rw-r--r-- 1 admin admin 2757  8月  3 13:56 Gemfile.lock
drwxr-xr-x 1 admin admin  102  8月  3 13:52 vendor


[admin@localhost HelloRuby]$ bundle exec rails new my1stRails --skip-spring
      create
      create  README.md
      create  Rakefile
      create  config.ru
      create  .gitignore
      create  Gemfile
      create  app
.............
Bundle complete! 13 Gemfile dependencies, 61 gems now installed.
Use `bundle show [gemname]` to see where a bundled gem is installed.

[admin@localhost HelloRuby]$ cd my1stRails
[admin@localhost my1stRails]$ bundle install --path vendor/bundle
Fetching gem metadata from https://rubygems.org/..........
.............
Bundle complete! 13 Gemfile dependencies, 61 gems now installed.
Bundled gems are installed into ./vendor/bundle.

[admin@localhost my1stRails]$ bundle exec rails server
/home/admin/.anyenv/envs/rbenv/versions/2.3.0/lib/ruby/gems/2.3.0/gems/bundler-1.12.5/lib/bundler/runtime.rb:89:in `rescue in block (2 levels) in require': There was an error while trying to load the gem 'uglifier'. (Bundler::GemRequireError)
Gem Load Error is: Could not find a JavaScript runtime. See https://github.com/rails/execjs for a list of available runtimes.
Backtrace for gem load error is:
.........

[admin@localhost my1stRails]$ vi Gemfile
gem 'therubyracer'

[admin@localhost my1stRails]$ bundle install --path vendor/bundle
......
Installing therubyracer 0.12.2 with native extensions
......
Bundle complete! 14 Gemfile dependencies, 64 gems now installed.
Bundled gems are installed into ./vendor/bundle.

[admin@localhost my1stRails]$ bundle exec rails server
=> Booting Puma
=> Rails 5.0.0 application starting in development on http://localhost:3000
........
* Listening on tcp://localhost:3000
Use Ctrl-C to stop

1.4 サーバー起動


[root@localhost tmp]# ss -natu
Netid  State      Recv-Q Send-Q                           Local Address:Port                                          Peer Address:Port
tcp    LISTEN     0      128                                          *:22                                                       *:*
tcp    LISTEN     0      128                                  127.0.0.1:3000                                                     *:*
tcp    LISTEN     0      100                                  127.0.0.1:25                                                       *:*
tcp    ESTAB      0      0                                 192.168.10.5:22                                            192.168.10.3:50992
tcp    ESTAB      0      0                                 192.168.10.5:22                                            192.168.10.3:49555
........

bundle exec rails server -b 192.168.10.5で192.168.10.5

にバインドします。

Netid  State      Recv-Q Send-Q                           Local Address:Port                                          Peer Address:Port
tcp    LISTEN     0      128                                          *:22                                                       *:*
tcp    LISTEN     0      128                               192.168.10.5:3000                                                     *:*
tcp    LISTEN     0      100                                  127.0.0.1:25                                                       *:*
tcp    ESTAB      0      0                                 192.168.10.5:22                                            192.168.10.3:50992
tcp    ESTAB      0      0                                 192.168.10.5:22                                            192.168.10.3:49555
tcp    ESTAB      0      0                                 192.168.10.5:3000                                          192.168.10.3:52873
tcp    ESTAB      0      0                                 192.168.10.5:3000                                          192.168.10.3:52872
........

MACのブラウザにhttp://192.168.10.5:3000/と入力
「Yay! You’re on Rails!と表示されて無事終了です」

2. Hello World etc

とりあえず、Atomで生成されたProjectディレクトリを参照します。
参考を見つつHelloWorldしましょう。

2.1 MVC用のコントローラー追加

[admin@localhost my1stRails]$ bundle exec rails g controller example1
      create  app/controllers/example1_controller.rb
      invoke  erb
      create    app/views/example1
      invoke  test_unit
      create    test/controllers/example1_controller_test.rb
      invoke  helper
      create    app/helpers/example1_helper.rb
      invoke    test_unit
      invoke  assets
      invoke    coffee
      create      app/assets/javascripts/example1.coffee
      invoke    scss
      create      app/assets/stylesheets/example1.scss
  1. コントローラー追加
my1stRails/app/controllers/example1_controller.rb
class Example1Controller < ApplicationController
  def default
end
  1. ビュー追加
my1stRails/app/views/example1/default.html.erb
<h1>Hello ruby controller<h1>
  1. ルーティングを設定
my1stRails/config/routes.rb
Rails.application.routes.draw do
  get 'example1' => 'Example1#default'
end
  1. 再起動
[admin@localhost my1stRails]$ bundle exec rails server -b 192.168.10.5

2.2 APIのみアプリ作成

Rails5からの新機能なので使ってみます。HelloRubyの下まで戻ります。
もう一回projectを作成する所からやり直しです。
こちらを参考にして進めます。

[admin@localhost HelloRuby]$ rails new my1stAPI --api
..........
* bin/rake: spring inserted
* bin/rails: spring inserted

[admin@localhost HelloRuby]$ cd my1stAPI
[admin@localhost my1stAPI]$ bundle install --path vendor/bundle
..........
Installing rails 5.0.0
Bundle complete! 8 Gemfile dependencies, 48 gems now installed.
Bundled gems are installed into ./vendor/bundle.

下記のAPI設定がtrueになっている事を確認します。

my1stAPI/config/application.rb
.......
module My1stAPI
  class Application < Rails::Application
    config.api_only = true
    config.debug_exception_response_format = :default
    config.debug_exception_response_format = :api
  end
end
  1. コントローラー追加
my1stAPI/app/controllers/example2_controller.rb
class Example2Controller < ActionController::API
  def show
    @lang = {ruby:'matz', python:'guido', perl:'larry', lisp:'mccarthy'}
    render json: @lang
  end
end

  1. ルーティングを設定
my1stAPI/config/routes.rb
Rails.application.routes.draw do
  # For details on the DSL available within this file, see http://guides.rubyonrails.org/routing.html
  get 'example2' => 'example2#show'
end

記録

MVC版
https://github.com/MariMurotani/my1stRails

APIのみ版
https://github.com/MariMurotani/my1stAPI

3. Apache Passengerのインストール

VirtualBoxで共有フォルダをマウントしていた場合に、rails serverだと静的ファイルを更新しないのでコードを書いてて不便な事に気づきました。
というわけで、こちらを参考にapacheをインストールして適切にconfigをします。

[admin@localhost my1stAPI]$ gem install passenger
Fetching: passenger-5.0.30.gem (100%)
........
Done installing documentation for passenger after 50 seconds
1 gem installed
[admin@localhost my1stAPI]$ rbenv rehash
[admin@localhost my1stAPI]$ passenger-install-apache2-module
Welcome to the Phusion Passenger Apache 2 module installer, v5.0.30.
..............
Installation instructions for required software

 * To install Curl development headers with SSL support:
   Please install it with yum install libcurl-devel

 * To install Apache 2:
   Please install it with yum install httpd

 * To install Apache 2 development headers:
   Please install it with yum install httpd-devel

 * To install Apache Portable Runtime (APR) development headers:
   Please install it with yum install apr-devel

 * To install Apache Portable Runtime Utility (APU) development headers:
   Please install it with yum install apr-util-devel

If the aforementioned instructions didn't solve your problem, then please take
a look at our documentation for troubleshooting tips:

  https://www.phusionpassenger.com/library/install/apache/
  https://www.phusionpassenger.com/library/admin/apache/troubleshooting/

必要なソフトのインストール方法を指示してくれるので全てインストールします。
その後、passenger-install-apache2-moduleをしてapache用のsoをコンパイルします。

passenger-install-apache2-module --snippet

インストールされたモジュールが表示されるので、conf.d以下にrails.confを作成して#Passenger Configuration の部分を書き換えます。

rails.conf
# Ruby on Rails root
<VirtualHost *:3000>
    RailsEnv development
    PassengerEnabled on
    ServerName 192.168.10.5
    DocumentRoot /home/admin/share/HelloRuby/my1stAPI/public
    #RailsBaseURI /
  <Directory /home/admin/share/HelloRuby/my1stAPI/public>
    Require all granted
    Options FollowSymLinks
    AllowOverride None
    Order allow,deny
    Allow from all

    EnableMMAP Off
    EnableSendfile Off
  </Directory>
</VirtualHost>

# Passenger Configuration
LoadModule passenger_module /home/admin/.anyenv/envs/rbenv/versions/2.3.0/lib/ruby/gems/2.3.0/gems/passenger-5.0.30/buildout/apache2/mod_passenger.so
<IfModule mod_passenger.c>
  PassengerRoot /home/admin/.anyenv/envs/rbenv/versions/2.3.0/lib/ruby/gems/2.3.0/gems/passenger-5.0.30
  PassengerDefaultRuby /home/admin/.anyenv/envs/rbenv/versions/2.3.0/bin/ruby
</IfModule>

PassengerResolveSymlinksInDocumentRoot on
~

パーミッション系のエラーが出るので0755でマウントするように変更して親ディレクトリまできっちり755にしてやっとちゃんと起動しました。

mount -o uid=1000,gid=1000,fmode=0755,dmode=0755 -t vboxsf SharedCent7 /home/admin/share

service httpd configtest
systemctl start httpd
systemctl enable httpd

どうしてもコントローラーのキャッシュが効いてしまうので
取り急ぎコントローラーが変わらない場合は下記コマンドを手動実行するハメに・・・。

rails dev:cache

それだと遅いので取り急ぎ

touch mecabuserdic_controller.rb

で無理やりコマンドラインからファイル日時を変更してコントローラーのキャッシュをクリアしています。

何かいい方法ないのか・・・・。

2016/08/16:
結局WebDriveをマウントして使う事にしました。
-> 失敗。ファイルが更新されない問題が・・・

2016/08/23:
vboxfsでマウントして作業しているとコンパイルなどが遅くてイライラするので、
結局ゲストOS側にNFSDを起動させてMACにマウントする事にした。
これでちょっとはパフォーマンスは改善した模様。
メモ:
insecure,no_root_squashのオプションが必要だったのでメモ

/etc/exports
/home/admin/ 192.168.10.0/24(rw,async,insecure,no_root_squash)
8
7
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
8
7