AT's Blog

趣味のプログラミング、ギター、音楽とかとか

MacにrbenvでRuby仮想環境を構築する

先日、会社でRuby on Railsを用いて構築された設計支援Webアプリを目にする機会がありました。 私の業務で使用することはなさそうですが、内製ツールとは思えないクオリティで、触っていてワクワクしました。

ミーハーなので、これを機に私もRubyRailsに手を出してみたいと思います。

  • 開発環境
    • OS X Yosemite Ver.10.10.5(古いです…)
    • Homebrew 1.5.13
    • zsh 5.0.5

私のMacにデフォルトでインストールされているRubyはVer.2.0.0とかなり古かったので、rbenvでVer.2.5.0をインストールします。

rbenvを使用することで、複数のバージョンのRubyを同一システム内で簡単に使い分けることができます。 Pythonでいうpyenvですね。

なお、公式では脆弱性が修正されたVer.2.5.1がリリースされています(2018/03/31現在)

Ruby 2.5.1 リリース

まずは、仮想環境構築のためにrbenvをbrewでインストールします。

> brew install rbenv

rbenvでインストール可能なバージョンを確認します。

> rbenv install -l

今回は2.5.0をインストールします。

> rbenv install 2.5.0

システムにインストールされているバージョンを確認し、デフォルトから2.5.0に切り替えます。

> rbenv versions
rbenv versions
* system (set by /Users/xxx/.rbenv/version)
  2.5.0
>rbenv global 2.5.0

Rubyのバージョンを確認します。

> ruby -v
ruby -v
ruby 2.5.0p0 (2017-12-25 revision 61468) [x86_64-darwin14]

無事にインストールできました。

ただし、このままだとターミナルを立ち上げる度にデフォルトに戻ってしまうので、 下記のように、おまじないをシェルの設定ファイルに追記します。

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

なお、rbenvでよく使うコマンド一覧と、各コマンドのhelpは下記のように確認できます。

> rbenv
rbenv
rbenv 1.1.1
Usage: rbenv <command> [<args>]

Some useful rbenv commands are:
   commands    List all available rbenv commands
   local       Set or show the local application-specific Ruby version
   global      Set or show the global Ruby version
   shell       Set or show the shell-specific Ruby version
   install     Install a Ruby version using ruby-build
   uninstall   Uninstall a specific Ruby version
   rehash      Rehash rbenv shims (run this after installing executables)
   version     Show the current Ruby version and its origin
   versions    List all Ruby versions available to rbenv
   which       Display the full path to an executable
   whence      List all Ruby versions that contain the given executable

See `rbenv help <command>' for information on a specific command.
For full documentation, see: https://github.com/rbenv/rbenv#readme
> rbenv help install
rbenv help install
Usage: rbenv install [-f|-s] [-kpv] <version>
       rbenv install [-f|-s] [-kpv] <definition-file>
       rbenv install -l|--list
       rbenv install --version

  -l/--list          List all available versions
  -f/--force         Install even if the version appears to be installed already
  -s/--skip-existing Skip if the version appears to be installed already

  ruby-build options:

  -k/--keep          Keep source tree in $RBENV_BUILD_ROOT after installation
                     (defaults to $RBENV_ROOT/sources)
  -p/--patch         Apply a patch from stdin before building
  -v/--verbose       Verbose mode: print compilation status to stdout
  --version          Show version of ruby-build

For detailed information on installing Ruby versions with
ruby-build, including a list of environment variables for adjusting
compilation, see: https://github.com/rbenv/ruby-build#usage

以上です。