Rbenv install mac os

ZeroSharp

Robert Anderson’s ones and zeros

Installing Ruby With Homebrew and Rbenv on Mac OS X Mountain Lion

Jan 31 st , 2013 | Comments

Install Ruby with rbenv

I decided to setup Octopress on my Mac so that I can publish blog posts from either Windows or MacOS. I’m on OS X 10.8.2.

I tried to follow the Octopress instructions for installing Ruby but ran into a few problems.

Install Homebrew

Homebrew is a package manager for OS X. Open Terminal and install Homebrew with:

Once the installation is successful, you can run the following command to check your environment.

Apparently, you should see:

But instead I had 3 warnings.

This one can be fixed by modifying your .profile file. Create it if it doesn’t already exist. Use nano

/.profile if you don’t have a preferred editor.

Google tells me the other two warnings are related to Mono being installed and can be ignored.

Install rbenv

Rbenv handles the installation of multiple Ruby environments.

Install gcc

If I try to install Ruby immediately, I get

XCode used to ship with a compatible gcc, but no longer does. We can install it with Homebrew.

The new gcc will coexist happily alongside the default one.

Install Ruby 1.9.3

Now we can install Ruby.

Shouldn’t it say ruby 1.9.3? It turns out you need to add the following to the end of your .profile .

Now quit and restart Terminal.

Ruby 1.9.3 is installed correctly. If I quit and restart Terminal, ruby —version is still 1.9.3.

Posted by Robert Anderson Jan 31 st , 2013 homebrew, mac, octopress, rbenv, ruby

Источник

Установка Ruby on Rails с помощью rbenv в macOS

Ruby on Rails – один из самых популярных программных стеков для разработки сайтов и приложений. Он состоит из языка программирования Ruby и фреймворка Rails.

Ruby и Rails можно легко установить с помощью инструмента командной строки rbenv. Rbenv предоставляет надёжную среду для разработки приложений Ruby on Rails и позволяет переключать версии Ruby, сохраняя работу команды в одной версии.

Инструмент rbenv поддерживает настройку индивидуальных версий Ruby для каждого приложения, а также позволяет установить версию Ruby по умолчанию для каждого пользователя и переопределять версии Ruby с помощью переменных окружения.

Требования

  • Локальная или виртуальная машина macOS с правами администратора и доступом к интернету. Этот мануал выполнен на macOS 10.14 Mojave.
  • Установка Node.js на этой машине (вам поможет мануал Установка Node.js и настройка локальной среды разработки в macOS). От этой программы зависят некоторые функции Rails, например, Asset Pipeline.

1: Установка rbenv

Сначала мы установим rbenv и настроим автозапуск этого инструмента. Для этого используется менеджер Homebrew.

Чтобы установить rbenv при помощи Homebrew, введите:

brew install rbenv

Команда установит rbenv и плагин ruby-build. Этот плагин добавляет команду rbenv install, которая упрощает процесс установки новых версий Ruby.

Теперь нужно добавить команду eval “$(rbenv init -)” в файл

/.bash_profile, чтобы инструмент rbenv запускался автоматически вместе с терминалом. Откройте файл в текстовом редакторе:

Добавьте в него такую строку:

eval «$(rbenv init -)»

Сохраните и закройте файл.

Чтобы изменения вступили в силу в текущей сессии, нужно ввести команду:

Чтобы убедиться, что настройка инструмента rbenv прошла успешно, используйте команду type:

В терминале появится такой вывод:

rbenv is a function
rbenv ()
<
local command;
command=»$<1:->«;
if [ «$#» -gt 0 ]; then
shift;
fi;
case «$command» in
rehash | shell)
eval «$(rbenv «sh-$command» «$@»)»
;;
*)
command rbenv «$command» «$@»
;;
esac
>

Читайте также:  Драйвер для принтера canon mf3228 для windows 10 x64

Теперь можно установить Ruby.

2: Установка Ruby

Плагин ruby-build позволяет установить любую доступную версию Ruby с помощью одной простой команды. Запросите список версий Ruby, добавив в команду флаг –l:

rbenv install -l

Команда вернёт длинный список версий, доступных для установки.

Выберите нужную версию и установите её.

В данном мануале мы установим Ruby 2.6.3.

rbenv install 2.6.3

Процесс установки Ruby может занять много времени.

После установки вы можете настроить эту версию Ruby в качестве версии по умолчанию. Для этого используется подкоманда global.

rbenv global 2.6.3

Чтобы убедиться, что установка Ruby прошла успешно, запросите версию:

Команда должна вернуть:

ruby 2.6.3p62 (2019-04-16 revision 67580) [x86_64-darwin18]

Чтобы установить другую версию Ruby, просто укажите ее в команде вместо 2.6.3. Например:

rbenv install 2.3.0
rbenv global 2.3.0

Теперь у вас есть одна версия Ruby, которую вы настроили как версию по умолчанию. Далее мы поработаем с пакетами и библиотеками Ruby – так называемыми gem-ами, с помощью которых можно установить Rails.

3: Установка и использование gem-ов

Gem-ы – это пакеты, с помощью которых можно расширить функции Ruby. Rails является gem-ом, потому его можно установить с помощью команды gem.

Когда вы устанавливаете gem, процесс генерирует локальную документацию. Это может значительно затянуть установку каждого gem-а. Лучше отключите локальную документацию, создав файл

/.gemrc (он содержит параметр конфигурации для отключения этой функции):

echo «gem: —no-document» >

Затем установите gem Bundler, инструмент, который управляет зависимостями приложений.

gem install bundler

Fetching: bundler-2.0.2.gem
Successfully installed bundler-2.0.2
1 gem installed

Команда gem env (env – это сокращение от environment) предоставляет сведения о среде и настройке gem-ов. Чтобы узнать, куда устанавливаются gem-ы, запустите её с аргументом home.

4: Установка Rails

Чтобы установить Rails, введите команду gem install с флагом –v, который позволяет указать версию:

gem install rails -v 5.2.3

Команда gem устанавливает указанный вами gem, а также все его зависимости. Rails является сложной средой веб-разработки и зависит от многих пакетов, поэтому установка займет некоторое время. В конце вы увидите сообщение о том, что Rails и все зависимости были установлены:


Successfully installed rails-5.2.3
38 gems installed

Примечание: Если вы хотите установить другую версию Rails, вы можете получить список поддерживаемых версий. Для этого выполните поиск, который выведет длинный список возможных версий. Затем можно установить какую-то другую версию, к примеру, 4.2.7:

gem search ‘^rails$’ —all
gem install rails -v 4.2.7

Если вы хотите установить последнюю версию Rails, запустите команду, не указывая версии:

gem install rails

Инструмент rbenv создаёт каталог shim-ов, которые перехватывают вызовы и изменяют или перенаправляют их. В этом случае shim-ы направляют команды Ruby на файлы, используемые текущей включенной версией Ruby. С помощью подкоманды rehash инструмент rbenv поддерживает в этом каталоге shim-ы для всех команд и всех версий Ruby, установленных на вашем сервере. Потому после установки новой версии или gem-а нужно запускать команду:

Чтобы убедиться в том, что установка Rails прошла успешно, запросите установленную версию:

Если установка прошла без ошибок, вы увидите:

5: Обновление и удаление rbenv и Ruby

При управлении проектами полезно знать, как при необходимости обновлять и удалять их компоненты. Сейчас мы обновим rbenv, а затем удалим Ruby и rbenv со своего компьютера.

Обновить rbenv и ruby-build можно с помощью Homebrew:

brew upgrade rbenv ruby-build

Если rbenv или ruby-build нуждается в обновлении, Homebrew автоматически обновит их. Если же ваши экземпляры уже обновлены, вы получите такой вывод:

Error: rbenv 1.1.2 already installed
Error: ruby-build 20190615 already installed

Это значит, что на вашей машине уже используется последняя версия rbenv.

Все версии собираются в каталоге

/.rbenv/versions, и со временем он может переполниться. Если какая-то версия Ruby больше не нужна, её можно удалить. Для этого плагин ruby-build предоставляет подкоманду uninstall.

К примеру, чтобы удалить версию 2.1.3, нужно ввести команду:

rbenv uninstall 2.1.3

С помощью команды rbenv uninstall вы можете очистить старые версии Ruby, чтобы у вас не было установлено больше версий, чем вы используете в настоящее время.

Если вы решили удалить rbenv, откройте в редакторе файл

Найдите и удалите из него эту строку, чтобы rbenv больше не запускался вместе с терминалом:

Сохраните и закройте файл.

Чтобы обновления вступили в силу в текущей сессии, введите:

Читайте также:  Как перезапустить службу windows 10 через командную строку

Затем можно удалить rbenv и все установленные версии Ruby с помощью этой команды:

rm -rf `rbenv root`

Теперь нужно удалить пакет rbenv из Homebrew:

brew uninstall rbenv

Чтобы убедиться, что инструмент удален, запросите его версию:

Вы получите такой вывод:

-bash: /usr/local/bin/rbenv: No such file or directory

Это значит, что rbenv удален с машины.

Заключение

Вы знакомы с основами работы с rbenv, можете установить Ruby on Rails и управлять различными окружениями Ruby.

Теперь нужно защитить приложение. Вместо стандартной БД sqlite3 в приложениях Ruby on Rails рекомендуется использовать более надёжную СУБД, например PostgreSQL.

Источник

Mischa Taylor’s Coding Blog

On the edge of time and reason

Using Rbenv to Manage Multiple Versions of Ruby

Jun 15 th , 2013

Updated December 15th, 2013:

  • Updated install link for homebrew, it has changed
  • Updated Xcode install instructions for Mac OS X Mavericks
  • Bumped ruby 1.9.3 version from 1.9.3p448 to 1.9.3p484
  • Bumped ruby 2.0.0 version from 2.0.0p247 to 2.0.0p353

Updated July 9th, 2013:

  • Bumped ruby 1.9.3 version from 1.9.3p429 to 1.9.3p448
  • Bumped ruby 2.0.0 version from 2.0.0p195 to 2.0.0p247
  • Removed openssl workaround for compiling ruby 2.0.0 on Mac OS X — this has been fixed

Out of the box, Ruby does not provide a mechanism to support multiple installed versions. Rbenv makes managing multiple versions of Ruby easy. It’s a great way to work on current development projects using Ruby 1.9.x and be able to switch to Ruby 2.0.x for new work. Rbenv is a lightweight alternative to Ruby Version Manager (RVM). Rbenv does not include a way to manage gems, like with RVM, though most people prefer to use Bundler gem management instead.

Rbenv is supported on Linux and Mac OS X. Rbenv doesn’t work on Windows (and isn’t really necessary on Windows as there is no system Ruby on Windows). On Windows, the RubyInstaller and/or Pik are both good alternatives to work with multiple versions of Ruby on the same box.

NOTE: Rbenv is incompatible with RVM because RVM overrides the gem command with a function. If you want to switch to Rbenv, make sure you uninstall RVM first. Run the following commands to uninstall RVM:

Then remove/comment out the RVM loader line in .bash_profile and/or .bashrc

Mac OS X

Install Rbenv and Ruby 1.9.x — Mac OS X

First you’ll need to install a C compiler and some other command line tools to build Ruby from source. You’ll need to install the Xcode Command Line Tools:

Mac OS X Mavericks 10.9

If you are using the latest version of Mac OS X Mavericks, it has support for downloading the Xcode command line tools directly from a Terminal window. Run the following on a command line:

You will be prompted to either click on Install to just install the command line developer tools or click on Get Xcode to install both Xcode and the command line developer tools. It can be handy to have Xcode as well, but it is a rather large multi-gigabyte download and not really necessary for Ruby development. So if you want to get going quickly, just click on the Install button:

Mac OS X Snow Leopard 10.8 (and earlier)

Versions of Mac OS X prior to Mavericks, like Snow Leopard do not have built-in support for downloading the Xcode command line developer tools, but you can download them directly from the Apple Developer web site developer.apple.com/downloads. Here are the current direct download links for the Xcode command line tools as of this writing. Download the applicable package for your version of Mac OS X:

Once you have downloaded the .dmg file, double-click on the .dmg to open it, then double-click on the .mpkg file to run the Command Line Tools installer:

If you have time to install Xcode, it’s handy to have it around, though not really required for Ruby development. If you are running Mac OS X Mountain Lion 10.8, you will need to make sure that you have OS X version 10.8.4 or later to install Xcode, otherwise the App Store will issue the following complaint:

Download and install the latest version of Xcode from the App Store. Then install the Command Line Tools by choosing the menu item Xcode -> Preferences. to display the Downloads dialog. Click on the Downloads tab, then click on the download arrow to the right of the Command Line Tools component to install.

Читайте также:  Monitoring cpu temperature windows

Next, you’ll need to install the Homebrew package manager to get all the dependencies needed to compile Ruby from source. While you could manage these dependencies by hand, using a package manager is a better idea, as package managers know how to uninstall what they install.

Run the following command to install Homebrew:

Run brew doctor and address any issues it discovers. When all is well, you should see:

Next, install the additional dependencies to compile Ruby from source:

And now install rbenv and the ruby-build plugin:

Add rbenv init to your shell to enable shims and autocompletion:

Restart shell as a login shell so that the PATH changes take effect:

Install the latest version of ruby 1.9.x (at the time of this writing 1.9.3-p484)

Rebuild the shim executable

You’ll need to run rbenv rehash every time you install a new version of Ruby or install a new gem.

Set the latest version of ruby to be the default version of ruby

Verify the ruby install. If everything was installed correctly, the ruby -v command should report that version 1.9.3p484 is installed.

Install Bundler — Mac OS X

You’ll need to use Bundler to manage gems. Installing a gem is also a good way to ensure that you’ve installed most of the Ruby prerequisites.

First, make sure you update to the latest version of Rubygems:

Then install the bundler gem. If the gem install command reports Successfully installed you’re good to go:

Install Ruby 2.0.0 — Mac OS X

As of this writing, Ruby 2.0.0-p353 is the latest version of Ruby 2.0.0. Use rbenv install —list to print out the available versions. To install:

To verify the install:

If you want to make Ruby 2.0.0 the global default version of ruby:

Upgrade Rbenv — Mac OS X

To upgrade rbenv via homebrew:

Remove Rbenv — Mac OS X

Uninstall the packages you installed via homebrew:

Remove the following directory:

And remember to remove whatever you added to $HOME/.bash_profile

Linux

Install Rbenv and Ruby 1.9.x — Linux

Make sure the prerequisite packages are installed.

Download the rbenv source distribution to $HOME/.rbenv:

Add $HOME/.rbenv/bin to your $PATH

Add rbenv init to your shell to enable shims and autocompletion:

Restart shell as a login shell so that the PATH changes take effect:

Install the ruby-build plugin, which provides an rbenv install command to simplify the process of compiling and install new Ruby versions:

Install the latest version of ruby 1.9.x (at the time of this writing 1.9.3-p484)

Rebuild the shim executable

You’ll need to run rbenv rehash every time you install a new version of Ruby or install a new gem.

Set the latest version of ruby to be the default version of ruby

Verify the ruby install. If everything was installed correctly, the ruby -v command should report that version 1.9.3p484 is installed.

Install Bundler — Linux

You’ll need to use Bundler to manage gems. Installing a gem is also a good way to ensure that you’ve installed most of the Ruby prerequisites.

First, make sure you update to the latest version of Rubygems:

Then install the bundler gem. If the gem install command reports Successfully installed you’re good to go:

Install Ruby 2.0.0 — Linux

As of this writing, Ruby 2.0.0-p353 is the latest version of Ruby 2.0.0. Use rbenv install —list to print out the available versions. To install:

To verify the install:

If you want to make Ruby 2.0.0 the global default version of ruby (but currently Chef requires Ruby 1.9.x):

Upgrade Rbenv — Linux

Since Rbenv is a Git repository, upgrading is just a matter of refreshing the source:

Remove Rbenv — Linux

To uninstall/remove Rbenv, remove the following directory:

And remember to remove whatever you added to $HOME/.bash_profile

Posted by Mischa Taylor Jun 15 th , 2013 ruby

Recent Posts

GitHub Repos

Copyright © 2014 — Mischa Taylor — Powered by Octopress

Источник

Оцените статью