Matthewの備忘録

忘れたときはここを見ろ。何か書いてある。

Ubuntu上RailsとRVM環境覚書

 Rails 3.1も出たし、書き直しておく。

 骨子をいうと、gemsetを次のように用意し、運用するということである。

  • global gemset : rake しかない
  • passenger gemset : passenger 用
  • rails3.1 gemset : 素のrails3.1しかない
  • 任意のRailsアプリ gemset: rails3.1からgemsetをコピーして使う
  • Rails以外用の gemset : rvm gemset createを実行
  • ・・・

 なお、このインストール作業直前はRubyUbuntuにインストールされていない。

 さて、いろいろなサイトを参考に、RVMとRails環境のユニバーサルインストール。rootでインストールすると「適当に」共有領域にインストールしてくれて、どのユーザーからでも使える、ユーザは個別の設定で使える、という便利な環境を作り出せる。ということで、面倒なので、rootユーザになっておく(笑)。

$ sudo su
#

 まずは、curlとgit。curlはダウンロードするのに必要。

# apt-get install curl git

 つぎにRVMをダウンロード&インストールする。https://rvm.beginrescueend.com/install/rvmをみるとスクリプト中にgit checkoutなどのセンテンスがみられる。

# bash < <(curl -s https://rvm.beginrescueend.com/install/rvm)

Successfully checked out branch ''
remote: Counting objects: 14, done.
remote: Compressing objects: 100% (3/3), done.
remote: Total 8 (delta 5), reused 8 (delta 5)
Unpacking objects: 100% (8/8), done.
From git://github.com/wayneeseguin/rvm
   aafd398..d41945c  master     -> origin/master
First, rewinding head to replay your work on top of it...
Fast-forwarded master to d41945c7adfe6f14f53a5740bd22cbc210acc4d3.
Successfully pulled (rebased) from origin 

  RVM:  Shell scripts enabling management of multiple ruby environments.
  RTFM: https://rvm.beginrescueend.com/
  HELP: http://webchat.freenode.net/?channels=rvm (#rvm on irc.freenode.net)
  
Installing RVM to /usr/local/rvm/
    Correct permissions for base binaries in /usr/local//bin...
    Copying manpages into place.
RVM system user group 'rvm' exists, proceeding with installation.


Notes for Linux ( DISTRIB_ID=Ubuntu
DISTRIB_RELEASE=11.04
DISTRIB_CODENAME=natty
DISTRIB_DESCRIPTION="Ubuntu 11.04" )

NOTE: 'ruby' represents Matz's Ruby Interpreter (MRI) (1.8.X, 1.9.X)
             This is the *original* / standard Ruby Language Interpreter
      'ree'  represents Ruby Enterprise Edition
      'rbx'  represents Rubinius

bash >= 3.2 is required
curl is required
git is required (>= 1.7 recommended)
patch is required (for ree and some ruby-head's).

If you wish to install rbx and/or Ruby 1.9 head (MRI) (eg. 1.9.2-head),
then you must install and use rvm 1.8.7 first.

If you wish to have the 'pretty colors' again,
  set 'export rvm_pretty_print_flag=1' in ~/.rvmrc.

dependencies:
# For RVM
  rvm: bash curl git

# For Ruby (MRI & ree)  you should install the following OS dependencies:
  ruby: /usr/bin/apt-get install build-essential bison openssl libreadline6 libreadline6-dev curl git-core zlib1g zlib1g-dev libssl-dev libyaml-dev libsqlite3-0 libsqlite3-dev sqlite3 libxml2-dev libxslt-dev autoconf libc6-dev ncurses-dev

# For JRuby (if you wish to use it) you will need:
  jruby: /usr/bin/apt-get install curl g++ openjdk-6-jre-headless
  jruby-head: /usr/bin/apt-get install ant openjdk-6-jdk

# In addition to ruby: dependencies,
  ruby-head: subversion

# For IronRuby (if you wish to use it) you will need:
  ironruby: /usr/bin/apt-get install curl mono-2.0-devel

For rbx (Rubinius) more than 600MB of free RAM required.


Installation of RVM to /usr/local/rvm/ is complete.


root,

Thank you very much for using RVM! I sincerely hope that RVM helps to
make your life both easier and more enjoyable.

If you have any questions, issues and/or ideas for improvement please
join#rvm on irc.freenode.net and let me know, note you must register
(http://bit.ly/5mGjlm) and identify (/msg nickserv <nick> <pass>) to
talk, this prevents spambots from ruining our day.

My irc nickname is 'wayneeseguin' and I hang out in #rvm typically

  ~09:00-17:00EDT and again from ~21:00EDT-~23:00EDT

If I do not respond right away, please hang around after asking your
question, I will respond as soon as I am back.  It is best to talk in
#rvm itself as then other users can help out should I be offline.

Be sure to get head often as rvm development happens fast,
you can do this by running 'rvm get head' followed by 'rvm reload'
or opening a new shell

  w&#10687;&#8255;&#10687;t

    ~ Wayne

 Mat'zのRuby(MRI)を直ぐにインストールしたいところだが、ビルドしてからのインストールとなるので、必要なパッケージを入れておく。必要なパッケージ名は上記のメッセージに出力されているのでしたがう。JRubyなどを使うときも同様だ。今回はとりあえず、全てそろえておく。

# apt-get install build-essential bison openssl libreadline6 libreadline6-dev curl git-core zlib1g zlib1g-dev libssl-dev libyaml-dev libsqlite3-0 libsqlite3-dev sqlite3 libxml2-dev libxslt-dev autoconf libc6-dev ncurses-dev
・・・
# apt-get install curl g++ openjdk-6-jre-headless
・・・
# apt-get install ant openjdk-6-jdk
・・・
# apt-get install curl mono-2.0-devel

 早速MRIをインストールしたいが、1.9.2系のMRIをインストールしたければ最初にVer.1.8.7をインストールしなければならない。さてどの1.8.7のうち最新環境を整えたい場合は、最新パッチレベルのがよいのかそれともheadのがよいのか?とりあえず、何が利用できるかしらべてみる。

# rvm list known
# MRI Rubies
[ruby-]1.8.6[-p420]
[ruby-]1.8.6-head
[ruby-]1.8.7[-p352]
[ruby-]1.8.7-head
[ruby-]1.9.1-p378
[ruby-]1.9.1[-p431]
[ruby-]1.9.1-head
[ruby-]1.9.2[-p180]
[ruby-]1.9.2-head
ruby-head

# GoRuby
goruby

# JRuby
jruby-1.2.0
jruby-1.3.1
jruby-1.4.0
jruby-1.6.1
jruby[-1.6.2]
jruby-head

# Rubinius
rbx-1.0.1
rbx-1.1.1
rbx-1.2.3
rbx[-head]
rbx-2.0.0pre

# Ruby Enterprise Edition
ree-1.8.6
ree[-1.8.7][-2011.03]
ree-1.8.6-head
ree-1.8.7-head

# Kiji
kiji

# MagLev
maglev[-26063]
maglev-head

# Mac OS X Snow Leopard Only
macruby[-0.10]
macruby-nightly
macruby-head

# IronRuby -- Not implemented yet.
ironruby-0.9.3
ironruby-1.0-rc2
ironruby-head

わからなかったので、とりあえずheadをインストールしてしまえ!どうせ削除ができるのだから。

# rvm install 1.8.7-head

一般ユーザで行うときはrvmsudo rvm install 1.8.7-headを実行するとよい(環境が悪いと結構時間がかかるよ)。rubygems-1.6.2も同時にインストールされる。

1.9.2も同様に行う。

# rvm install 1.9.2-head

インストールするとこうなる。

# rvm list

rvm rubies

   ruby-1.9.2-head [ i386 ]
   ruby-1.8.7-head [ i386 ]

 ローカルユーザーがrubyを使えるようにしておく。

$ ruby -v
rubyがないなどのエラーメッセージがでる

# rvm --default use 1.9.2-head
Using /usr/local/rvm/gems/ruby-1.9.2-head

$ ruby -v
ruby 1.9.2p290 (2011-07-09 revision 32478) [i686-linux]

 gemはユーザー毎に管理すべきだと思うので、ここからはローカルユーザーでインストールを行う。

 rvmをインストールするとき、ローカルユーザーであれば、.bashrcなどに記述追加すべきセンテンスが示されるのだが、rootユーザでインストールすると出力されないようだ。.profileや.bashrcなどに個別に書くのもよいが、みんなで使う場合もあるだろうから、とりあえず共有部分は/etc/profileに書き足しておこうと思ったが、各自の~/.bashrcの文末に次の1行を追加する。

[[ -s "/usr/local/rvm/scripts/rvm" ]] && . "/usr/local/rvm/scripts/rvm"

sourceコマンドで反映させるか新しくシェルを立ち上げればよい。

$ source ~/.bashrc

一応、rvmが関数として動くのかどうか確かめた。

$ type rvm | head -1
rvm は関数です

関数と表示されればよし。

 実際のデプロイ先は/usr/local/rvm/gems/以下にgemsetが作成されていればよいと思うが、開発時はユーザー毎にgemsetを管理して欲しい。最低でも、Railsの初期のgemsetだけrootに持たせて、コピーして使って欲しいなど。とりあえず、gemsudoをつかって、rootとして、/usr/local/rvm/gems/にgemsetをおいてしまうことにした。rails 3.1の初期のgemだけがあるgemsetを作っておこう。

$ rvmsudo rvm gemset create rails3.1
[sudo] password for matthew: 
'rails3.1' gemset created (/usr/local/rvm/gems/ruby-1.9.2-head@rails3.1).

 rails最新版をインストールする。インストールするgemsetを確認してから行おう。

$ rvm gemset list

gemsets for ruby-1.9.2-head (found in /usr/local/rvm/gems/ruby-1.9.2-head)
   global
=> rails3.1

matthew@luke:~$ rvmsudo gem install rails 
Fetching: activesupport-3.0.9.gem (100%)
Fetching: builder-2.1.2.gem (100%)
Fetching: i18n-0.5.0.gem (100%)
Fetching: activemodel-3.0.9.gem (100%)
Fetching: rack-1.2.3.gem (100%)
Fetching: rack-test-0.5.7.gem (100%)
Fetching: rack-mount-0.6.14.gem (100%)
Fetching: tzinfo-0.3.29.gem (100%)
Fetching: abstract-1.0.0.gem (100%)
Fetching: erubis-2.6.6.gem (100%)
Fetching: actionpack-3.0.9.gem (100%)
Fetching: arel-2.0.10.gem (100%)
Fetching: activerecord-3.0.9.gem (100%)
Fetching: activeresource-3.0.9.gem (100%)
Fetching: mime-types-1.16.gem (100%)
Fetching: polyglot-0.3.1.gem (100%)
Fetching: treetop-1.4.9.gem (100%)
Fetching: mail-2.2.19.gem (100%)
Fetching: actionmailer-3.0.9.gem (100%)
Fetching: thor-0.14.6.gem (100%)
Fetching: rdoc-3.8.gem (100%)
Fetching: railties-3.0.9.gem (100%)
Fetching: bundler-1.0.15.gem (100%)
Fetching: rails-3.0.9.gem (100%)
Successfully installed activesupport-3.0.9
Successfully installed builder-2.1.2
Successfully installed i18n-0.5.0
Successfully installed activemodel-3.0.9
Successfully installed rack-1.2.3
Successfully installed rack-test-0.5.7
Successfully installed rack-mount-0.6.14
Successfully installed tzinfo-0.3.29
Successfully installed abstract-1.0.0
Successfully installed erubis-2.6.6
Successfully installed actionpack-3.0.9
Successfully installed arel-2.0.10
Successfully installed activerecord-3.0.9
Successfully installed activeresource-3.0.9
Successfully installed mime-types-1.16
Successfully installed polyglot-0.3.1
Successfully installed treetop-1.4.9
Successfully installed mail-2.2.19
Successfully installed actionmailer-3.0.9
Successfully installed thor-0.14.6
Successfully installed rdoc-3.8
Successfully installed railties-3.0.9
Successfully installed bundler-1.0.15
Successfully installed rails-3.0.9
24 gems installed
Installing ri documentation for activesupport-3.0.9...
Installing ri documentation for builder-2.1.2...
unable to convert "\xF1" from ASCII-8BIT to UTF-8 for README, skipping
Installing ri documentation for i18n-0.5.0...
Installing ri documentation for activemodel-3.0.9...
Installing ri documentation for rack-1.2.3...
Installing ri documentation for rack-test-0.5.7...
Installing ri documentation for rack-mount-0.6.14...
Installing ri documentation for tzinfo-0.3.29...
Installing ri documentation for abstract-1.0.0...
Installing ri documentation for erubis-2.6.6...
Installing ri documentation for actionpack-3.0.9...
Installing ri documentation for arel-2.0.10...
Installing ri documentation for activerecord-3.0.9...
Installing ri documentation for activeresource-3.0.9...
Installing ri documentation for mime-types-1.16...
Installing ri documentation for polyglot-0.3.1...
Installing ri documentation for treetop-1.4.9...
Installing ri documentation for mail-2.2.19...
Installing ri documentation for actionmailer-3.0.9...
Installing ri documentation for thor-0.14.6...
Installing ri documentation for rdoc-3.8...
Installing ri documentation for railties-3.0.9...
Installing ri documentation for bundler-1.0.15...
Installing ri documentation for rails-3.0.9...
file 'lib' not found
Installing RDoc documentation for activesupport-3.0.9...
Installing RDoc documentation for builder-2.1.2...
unable to convert "\xF1" from ASCII-8BIT to UTF-8 for README, skipping
Installing RDoc documentation for i18n-0.5.0...
Installing RDoc documentation for activemodel-3.0.9...
Installing RDoc documentation for rack-1.2.3...
Installing RDoc documentation for rack-test-0.5.7...
Installing RDoc documentation for rack-mount-0.6.14...
Installing RDoc documentation for tzinfo-0.3.29...
Installing RDoc documentation for abstract-1.0.0...
Installing RDoc documentation for erubis-2.6.6...
Installing RDoc documentation for actionpack-3.0.9...
Installing RDoc documentation for arel-2.0.10...
Installing RDoc documentation for activerecord-3.0.9...
Installing RDoc documentation for activeresource-3.0.9...
Installing RDoc documentation for mime-types-1.16...
Installing RDoc documentation for polyglot-0.3.1...
Installing RDoc documentation for treetop-1.4.9...
Installing RDoc documentation for mail-2.2.19...
Installing RDoc documentation for actionmailer-3.0.9...
Installing RDoc documentation for thor-0.14.6...
Installing RDoc documentation for rdoc-3.8...
Installing RDoc documentation for railties-3.0.9...
Installing RDoc documentation for bundler-1.0.15...
Installing RDoc documentation for rails-3.0.9...
file 'lib' not found

libがないと言われているが、どうなんだろう?(放置)。因みに、上記はRails 3.0.9 rcのログである。3.1へアップデートするには、

$ rvmsudo gem update --system # システム全体
$ rvmsudo gem update rails    # railsのアップデート

を実行すればよい。

 DBにMySQLしか使わないのであれば、mysql2 gemもインストールしておく。インストール前にmysql-server、mysql-client、そしてブラウザから管理できるようにphpMyAdminをインストールしておくと、一部の作業が楽になるだろう。この他に重要なのがOSのmysql開発用パッケージであり、RH系ならmysql-develop、Ubuntuならlibmysqlclient-devパッケージが必要である。またついでにApache2もインストールしておくこと。

$ rvmsudo gem install mysql2
Building native extensions.  This could take a while...
Successfully installed mysql2-0.3.6
1 gem installed
Installing ri documentation for mysql2-0.3.6...
Enclosing class/module 'mMysql2' for class Result not known
Enclosing class/module "cMysql2Result" for alias size count not known
Installing RDoc documentation for mysql2-0.3.6...
Enclosing class/module 'mMysql2' for class Result not known
Enclosing class/module "cMysql2Result" for alias size count not known

へんなメッセージでてるけど、気にしないでおく。上記のようにしなくても、railsである程度つくったら、下記のようにbundle installを実行して、Gemfileにリストアップされている足りないgemをプロジェクトツリーのvendorディレクトリに自動で追加してくれる。

$ rvmsudo bundle install

とりあえず、bundle installなしで、つくってみて動くかどうか確かめる。

$ rails new hogehoge
      create  
      create  README
      create  Rakefile
      create  config.ru
      create  .gitignore
      create  Gemfile
      create  app
      create  app/controllers/application_controller.rb
      create  app/helpers/application_helper.rb
      create  app/mailers
      create  app/models
      create  app/views/layouts/application.html.erb
      create  config
      create  config/routes.rb
      create  config/application.rb
      create  config/environment.rb
      create  config/environments
      create  config/environments/development.rb
      create  config/environments/production.rb
      create  config/environments/test.rb
      create  config/initializers
      create  config/initializers/backtrace_silencers.rb
      create  config/initializers/inflections.rb
      create  config/initializers/mime_types.rb
      create  config/initializers/secret_token.rb
      create  config/initializers/session_store.rb
      create  config/locales
      create  config/locales/en.yml
      create  config/boot.rb
      create  config/database.yml
      create  db
      create  db/seeds.rb
      create  doc
      create  doc/README_FOR_APP
      create  lib
      create  lib/tasks
      create  lib/tasks/.gitkeep
      create  log
      create  log/server.log
      create  log/production.log
      create  log/development.log
      create  log/test.log
      create  public
      create  public/404.html
      create  public/422.html
      create  public/500.html
      create  public/favicon.ico
      create  public/index.html
      create  public/robots.txt
      create  public/images
      create  public/images/rails.png
      create  public/stylesheets
      create  public/stylesheets/.gitkeep
      create  public/javascripts
      create  public/javascripts/application.js
      create  public/javascripts/controls.js
      create  public/javascripts/dragdrop.js
      create  public/javascripts/effects.js
      create  public/javascripts/prototype.js
      create  public/javascripts/rails.js
      create  script
      create  script/rails
      create  test
      create  test/fixtures
      create  test/functional
      create  test/integration
      create  test/performance/browsing_test.rb
      create  test/test_helper.rb
      create  test/unit
      create  tmp
      create  tmp/sessions
      create  tmp/sockets
      create  tmp/cache
      create  tmp/pids
      create  vendor/plugins
      create  vendor/plugins/.gitkeep

    rails new ~/Code/Ruby/weblog

    This generates a skeletal Rails installation in ~/Code/Ruby/weblog.
    See the README in the newly created application to get going.
$ cd hogehoge/                   #この直後にrvmsudo bundle installをやるとよい(今回はいらない
                          #MySQLだとデータベースの用意をするが省略
                          #config/database.ymlの設定、rake db:create:allを実行
$ rails generate scaffold henyo pugya:string       #scaffold利用
      invoke  active_record
      create    db/migrate/20110714033326_create_henyos.rb
      create    app/models/henyo.rb
      invoke    test_unit
      create      test/unit/henyo_test.rb
      create      test/fixtures/henyos.yml
       route  resources :henyos
      invoke  scaffold_controller
      create    app/controllers/henyos_controller.rb
      invoke    erb
      create      app/views/henyos
      create      app/views/henyos/index.html.erb
      create      app/views/henyos/edit.html.erb
      create      app/views/henyos/show.html.erb
      create      app/views/henyos/new.html.erb
      create      app/views/henyos/_form.html.erb
      invoke    test_unit
      create      test/functional/henyos_controller_test.rb
      invoke    helper
      create      app/helpers/henyos_helper.rb
      invoke      test_unit
      create        test/unit/helpers/henyos_helper_test.rb
      invoke  stylesheets
      create    public/stylesheets/scaffold.css
matthew@luke:~/temp/hogehoge$ rake db:migrate               #これでデータベースにテーブルを作る
==  CreateHenyos: migrating ===================================================
-- create_table(:henyos)
   -> 0.0046s
==  CreateHenyos: migrated (0.0049s) ==========================================

matthew@luke:~/temp/hogehoge$ rake             #環境テスト
Loaded suite /usr/local/rvm/gems/ruby-1.9.2-head@ohoho/gems/rake-0.9.2/lib/rake/rake_test_loader
Started
.
Finished in 0.378073 seconds.

1 tests, 1 assertions, 0 failures, 0 errors, 0 skips

Test run options: --seed 3800
Loaded suite /usr/local/rvm/gems/ruby-1.9.2-head@ohoho/gems/rake-0.9.2/lib/rake/rake_test_loader
Started
.......
Finished in 1.042069 seconds.

7 tests, 10 assertions, 0 failures, 0 errors, 0 skips

Test run options: --seed 51341
$ rails server
=> Booting WEBrick
=> Rails 3.0.9 application starting in development on http://0.0.0.0:3000
=> Call with -d to detach
=> Ctrl-C to shutdown server

 とやって、http://localhost:3000にアクセスしていつもの画面がでればとりあえずO.K.だ。エラーがでていたらその都度解決するが、データベースまわりは次に整える(最初にやってもよい)。MySQLなどの環境が整ってなければエラーがでているはずだ。また、config/database.ymlにパスワードがないだけかもしれない。sqlite3ならばエラーはないだろう。"About your application’s environment"というリンクを押してエラーがなく、情報が表示されていればよい。上記の場合はデフォルトでsqlite3であった。さらに、scaffoldで作成したオブジェクトに対してCRUDができるか確認する。上記の場合はhttp://localhost:3000/henyosにアクセスして確かめることができる。

 次にMySQLデータベースとApache2 HTTP Serverをインストールする。最初にやっておいてもよかったが、ここでやる。

$ sudo apt-get install apache2 php5 php5-gd mysql-server php5-mysql phpmyadmin libapache2-mod-php5

libapache2-mod-php5はphpMyAdminが直ぐに動くように入れただけである。PHPapacheのモジュールとして動作するようになる(prefork MPM)。/var/www/test.phpというファイルを作成し、ブラウザでhttp://localhost/test.phpにアクセスして、一応PHPが動くか確認し、情報を得ておく。

<?php print_r (phpinfo()); ?>

 phpMyAdminであるが、Ubuntuのパッケージシステムならapt-getなどの実行時に連携して設定してくれて、いきなり使える状態になるのだが、一度にパッケージをインストールしていなかったときなど、連携して設定してくれていない場合は、次のようにリンクを張ってapache2の再起動をするだけでよい。

$ sudo ln -s /etc/phpmyadmin/apache.conf /etc/apache2/conf.d/phpmyadmin
$ sudo service apache2 restart

これでもおかしかったら自分で調べて考えなさい。

 MySQLが用意できたところで、MySQLを使うRailsのテストをする。上記と同様に行えばよい。

$ rails new huga
$ cd huga
$ rvmsudo bundle install
$ vi config/database.yml             #username, passwordなどを編集
$ rake db:create:all
$ rails g scaffold pu pi:string
$ rake db:migrate
$ rake
$ rails server

 
 passengerをインストールする。その前にapache2をインストールしておくこと。

 最初に、インストールしたapache2のバージョン確認をする。スレッド方式かプリフォーク方式か。apache2 -V コマンドを使ってどちらかを区別する。

$ apache2 -V
Server version: Apache/2.2.17 (Ubuntu)
Server built:   Feb 22 2011 18:33:02
Server's Module Magic Number: 20051115:25
Server loaded:  APR 1.4.2, APR-Util 1.3.9
Compiled using: APR 1.4.2, APR-Util 1.3.9
Architecture:   32-bit
Server MPM:     Prefork
  threaded:     no
    forked:     yes (variable process count)
Server compiled with....
 -D APACHE_MPM_DIR="server/mpm/prefork"
 -D APR_HAS_SENDFILE
 -D APR_HAS_MMAP
 -D APR_HAVE_IPV6 (IPv4-mapped addresses enabled)
 -D APR_USE_SYSVSEM_SERIALIZE
 -D APR_USE_PTHREAD_SERIALIZE
 -D SINGLE_LISTEN_UNSERIALIZED_ACCEPT
 -D APR_HAS_OTHER_CHILD
 -D AP_HAVE_RELIABLE_PIPED_LOGS
 -D DYNAMIC_MODULE_LIMIT=128
 -D HTTPD_ROOT="/etc/apache2"
 -D SUEXEC_BIN="/usr/lib/apache2/suexec"
 -D DEFAULT_PIDLOG="/var/run/apache2.pid"
 -D DEFAULT_SCOREBOARD="logs/apache_runtime_status"
 -D DEFAULT_LOCKFILE="/var/run/apache2/accept.lock"
 -D DEFAULT_ERRORLOG="logs/error_log"
 -D AP_TYPES_CONFIG_FILE="mime.types"
 -D SERVER_CONFIG_FILE="apache2.conf"

 上記のServer MPM、threaded、forkedあたりをみる。もしくは -D APACHE_MPM_DIR をみる。上記の場合だとMPMのPrefork版がインストールされているのがわかるだろう。この情報はpassengerをインストールするときに利用する。apache2のヘッダーファイルが必要なのだが、どちらのバージョンのヘッダーファイルが必要か知っておく必要がある。

 続いてPassengerのインストール。足りないライブラリがあれば教えてくれるので、まずはgemsetを調べてから、インストールコマンドを実行。今回の方針は、passenger専用のgemsetを作り、それを利用させることにした。他のgemsetを利用するRailsアプリケーションと独立させておくことができ、かつ、他のgemsetのアプリケーションを動かすことができる。つまり、passenngerを動かすのと、Railsアプリを動かすgemsetに何ら依存関係はないのである。

$ rvm gemset create passenger
...
$ rvm gemset use passenger
...
$ rvm gemset list
gemsets for ruby-1.9.2-head (found in /usr/local/rvm/gems/ruby-1.9.2-head)
   global
=> passenger
   rails3.1
$ rvmsudo gem install passenger

 続いて実行環境に応じたモジュールのビルド。apache2用のインストールスクリプトを実行する。

$ rvmsudo /usr/local/rvm/gems/ruby-1.9.2-head@passenger/bin/passenger-install-apache2-module

 * GNU C++ compiler... found at /usr/bin/g++
 * Curl development headers with SSL support... not found
 * OpenSSL development headers... found
 * Zlib development headers... foundls 
 * Ruby development headers... found
 * OpenSSL support for Ruby... found
 * RubyGems... found
 * Rake... found at /usr/local/rvm/wrappers/ruby-1.9.2-head@passenger/rake
 * rack... found
 * Apache 2... found at /usr/sbin/apache2
 * Apache 2 development headers... not found
 * Apache Portable Runtime (APR) development headers... not found
 * Apache Portable Runtime Utility (APU) development headers... not found
・・・

 上記のような感じで、一度止まってくれるので、スクリプトを止めて、足りないパッケージをインストールする。上記の場合、Ubuntuでは次のパッケージをインストールすれば見つけてくれる。

$ sudo apt-get libcurl4-openssl-dev apache2-prefork-dev

 再度、インストールスクリプトを実行。

$ rvmsudo /usr/local/rvm/gems/ruby-1.9.2-head@passenger/bin/passenger-install-apache2-module
Welcome to the Phusion Passenger Apache 2 module installer, v3.0.7.

This installer will guide you through the entire installation process. It
shouldn't take more than 3 minutes in total.

Here's what you can expect from the installation process:

 1. The Apache 2 module will be installed for you.
 2. You'll learn how to configure Apache.
 3. You'll learn how to deploy a Ruby on Rails application.

Don't worry if anything goes wrong. This installer will advise you on how to
solve any problems.

Press Enter to continue, or Ctrl-C to abort.

エンターを押して、継続。しばらくするとビルドに成功して次のように設定方法を教えてくれる。

The Apache 2 module was successfully installed.

Please edit your Apache configuration file, and add these lines:

   LoadModule passenger_module /usr/local/rvm/gems/ruby-1.9.2-head@passenger/gems/passenger-3.0.7/ext/apache2/mod_passenger.so
   PassengerRoot /usr/local/rvm/gems/ruby-1.9.2-head@passenger/gems/passenger-3.0.7
   PassengerRuby /usr/local/rvm/wrappers/ruby-1.9.2-head@passenger/ruby

After you restart Apache, you are ready to deploy any number of Ruby on Rails
applications on Apache, without any further Ruby on Rails-specific
configuration!

Press ENTER to continue.

更にエンターを押すと

Suppose you have a Rails application in /somewhere. Add a virtual host to your
Apache configuration file and set its DocumentRoot to /somewhere/public:

   <VirtualHost *:80>
      ServerName www.yourhost.com
      DocumentRoot /somewhere/public    # <-- be sure to point to 'public'!
      <Directory /somewhere/public>
         AllowOverride all              # <-- relax Apache security settings
         Options -MultiViews            # <-- MultiViews must be turned off
      </Directory>
   </VirtualHost>

And that's it! You may also want to check the Users Guide for security and
optimization tips, troubleshooting and other useful information:

  /usr/local/rvm/gems/ruby-1.9.2-head@passenger/gems/passenger-3.0.7/doc/Users guide Apache.html
ls
Enjoy Phusion Passenger, a product of Phusion (www.phusion.nl) :-)
http://www.modrails.com/

Phusion Passenger is a trademark of Hongli Lai & Ninh Bui.

これでビルドは終了。あとは設定だけ。まずはapache2の設定。既にapache2をインストールして起動しているとする。

 *.loadと*.confを作成して有効にしておく。

$ sudo vi mods-available/passenger.load
LoadModule passenger_module /usr/local/rvm/gems/ruby-1.9.2-head@passenger/gems/passenger-3.0.7/ext/apache2/mod_passenger.so
$ sudo vi mods-available/passenger.conf
PassengerRoot /usr/local/rvm/gems/ruby-1.9.2-head@passenger/gems/passenger-3.0.7
PassengerRuby /usr/local/rvm/wrappers/ruby-1.9.2-head@passenger/ruby
$ sudo a2enmod passenger

 とりあえず、アクセスできればよいので、以下のようにしてみる。

$ sudo vi sites-available/hoge
<VirtualHost *:80>
    ServerName hoge.co.jp
    ServerAdmin webmaster@hoge.co.jp
    DocumentRoot /home/matthew/temp/hoge/public
    ErrorLog /var/log/apache2/hoge.log
    LogLevel warn
    CustomLog /var/log/apache2/hoge-access.log combined
    RailsEnv development
    RailsBaseURI /
    <Directory /home/matthew/temp/hoge/public>
        Options -MultiViews
        AllowOverride None
    </Directory>
</VirtualHost>
$ sudo a2ensite hoge

 確認用に/etc/hostsも変更しておく。

$ sudo vi /etc/hosts
・・・
127.0.0.1       hoge.co.jp
・・・

apache2の設定変更を反映。

$ sudo service apache2 graceful

これでおおよそできた。あとはpassengerとは異なるgemsetのRailsプロジェクトを作ってみて確認。

$ rvm gemset use rails3.1
$ rails new hoge
$ cd hoge
$ rake db:create:all
$ rails generate scaffold ahaha ehehe:string
$ rake RAILS_ENV="{development,test,production}" db:migrate      #三つのうちのどれかを指定する
# vi /etc/apache2/sites-available/hoge
    VirtualHostとDirectoryで設定
    RailsEnv {development,test,production}                       #三つのうちのどれかを指定する。
    RailsBaseURI /
    を忘れないように
# service apache2 graceful

 さらに、使いやすくするために、Railsプロジェクトのトップディレクトリに.rvmrcを置いておく。そうすれば、プロジェクトのディレクトリに入っただけで、指定したgemsetを自動的に選択してくれる。

$ cd your_rails_top_directory
$ rvm --rvmrc --create ruby-1.9.2-head@your_gemset
$ cd ..
$ cd your_rails_top_directory  # 確認
初回は.rvmrcを信用するか尋ねられるので、YまたはEnterで信用させる。

 もしプロジェクト・アプリごとに変更ができなかったら次を試すとよい。

$HOME/.rvmrcに次を追加
rvm_project_rvmrc=1
変更しなくてよい場合は
rvm_project_rvmrc=0
デフォルトで決めておきたいときは
rvm_project_rvmrc_default=1
などとする。

 個々のプロジェクトのconfigに次のファイルを追加する。

config/setup_load_paths.rb

内容は

if ENV['MY_RUBY_HOME'] && ENV['MY_RUBY_HOME'].include?('rvm')
  begin
    rvm_path     = File.dirname(File.dirname(ENV['MY_RUBY_HOME']))
    rvm_lib_path = File.join(rvm_path, 'lib')
    $LOAD_PATH.unshift rvm_lib_path
    require 'rvm'
    RVM.use_from_path! File.dirname(File.dirname(__FILE__))
  rescue LoadError
    # RVM is unavailable at this point.
    raise "RVM ruby lib is currently unavailable."
  end
end

# Select the correct item for which you use below.
# If you're not using bundler, remove it completely.
#
# # If we're using a Bundler 1.0 beta
ENV['BUNDLE_GEMFILE'] = File.expand_path('../Gemfile', File.dirname(__FILE__))
require 'bundler/setup'
#
# # Or Bundler 0.9...
# if File.exist?(".bundle/environment.rb")
#   require '.bundle/environment'
# else
#   require 'rubygems'
#   require 'bundler'
#   Bundler.setup
# end

bundlerを利用する場合は、上記のENV['BUNDLE_GEMFILE']...require 'bundler/setup'の2行をコメントインさせる。

 以上で作業終了。http://hoge.co.jp/ahahasにアクセスしてみる。これでOK。rails側で何か変更したら

$ touch tmp/restart.txt

を実行すると、apache2/passengerが気づいて、自動的に更新される。

 新しく異なるgemsetを作るが、例えば上記で作ったrails3.1 gemsetに追加した新しいgemsetを作りたい場合はこうする:

$ rvm gemset copy your ruby-1.9.2-head@rails3.1 ruby-1.9.2-head@your_new_gemset

ただし、実行後に何らかのエラーが出る場合がある。コピー後のgemsetを確認して同じものがあればコピーできているので、心配はない(確かめた)。


参考: