Install rvm on windows

∞Installing RVM

RVM supports most UNIX like systems and Windows (with Cygwin or Bash on Ubuntu on Windows). The basic requirements are bash , curl , gpg2 and overall GNU version of tools — but RVM tries to autodetect it and install anything that is needed.

∞Install GPG keys

As a first step install GPG keys used to verify installation package:

In case you encounter an issues check security

∞Basic install

∞Ubuntu

RVM have dedicated Ubuntu package, so please follow instructions posted here: https://github.com/rvm/ubuntu_rvm

If you need a different (newer) version of RVM, after installing base version of RVM check the Upgrading section.

∞Any other system

Install RVM (development version):

Install RVM stable with ruby:

Additionally with rails (poor man’s railsinstaller):

Or with jruby, rails and puma:

To install without rubygems-bundler and rvm gems (and also remove those gems from both global.gems and default.gems):

To install with hirb gem (and also add it to global.gems):

To install with rails and haml gems (and also add them to default.gems):

For a progress bar when downloading RVM / Rubies:

Point to be noted is, there is a backslash before curl. This prevents misbehaving if you have aliased it with configuration in your

If you’re an existing RVM user and you don’t want RVM to attempt to setup your shell to load RVM, you can opt out of this at install time by exporting rvm_ignore_dotfiles=yes, or opt out permanently by setting this in your rvmrc.

∞You can also:

  • read the installation documentation below.
  • watch the most accurate (but not official) rvm screencast.
  • read the most accurate (but not official) rvm cheat sheet.
  • starting with Rails? watch the RailsCasts.com on Getting Started with Rails.

∞Installation explained

There are three different ways to install and configure RVM.

  1. Single-User installations ( recommended ) — For an isolated install within a user’s $HOME, not for root.
  2. Multi-User installations — For server administrators — For an installation usable by all users on the system — Please note that Single-User supersedes Multi-User. This also used to be called the System-Wide Install. Using this type of installation without knowledge how umask works is a big security risk.
  3. Mixed mode installations — For an installation usable by all users on the system — with isolated rubies/gemsets within a user’s $HOME. Installation instructions are exactly the same as for Multi-User installations, the difference is in users environment.

∞Installation

I recommend you read the installation script yourself. This will give you a chance to understand what it is doing before installing, and allow you to feel more comfortable running it if you do so.

∞1. Download and run the RVM installation script

Installing the stable release version:

To get the latest development state:

Instruct RVM to not change the shell initializations files ‘rc’ / ‘profile’:

Please note that from this point it is user responsibility to add sourcing rvm to appropriate files.

For a Multi-User install you would execute the following:

Note: The Multi-User install instructions must be prefixed with the sudo command. However, once the install is complete, and the instructions to add users to the rvm group is followed, the use of either sudo or rvmsudo is no longer required. The sudo command is only to temporarily elevate privileges so the installer can complete its work. If you need to use sudo or rvmsudo after the install is complete, some part of the install directions were not properly followed. This usually is because people execute the install as root , rather than executing the installation instructions from a non-privileged user account.

Installing a specific version:

Prefix the ‘bash’ portion with ‘sudo’, of course, if you wish to apply this to a Multi_user Install. Please feel free to check out our upgrading docs for more details on branch format.

Debugging installation process:

If the rvm install script complains about certificates you need to follow the displayed instructions.

Читайте также:  Occt windows 10 x32

Single-User Install Location:

If the install script is run as a standard, non-root user, RVM will install into the current users’s home directory.

Modification of user configuration files ( *rc / *profile ) — RVM by default will modify user startup files, although it is not recommended you can disable automated process and do this manually:

Multi-User Install Location: /usr/local/rvm

If the install script is run prefixed with sudo, RVM will automatically install into /usr/local/rvm . Please see the troubleshooting page for an important note regarding Multi-User Installs.

Please see the FAQ page for an important note regarding root only installs.

External tutorials

Note that that any outside tutorials are NOT supported whether they work or not. Tutorials are great, however we have spent massive amounts of man hours debugging the installation process. Please use the install process(es) from this site only, as this is the only supported installation types and methods.

To update an existing RVM installation

It is safe to simply re-run the installation script again, or you can follow the upgrading docs.

∞2. Load RVM into your shell sessions as a function

Single-User:

The rvm function will be automatically configured for every user on the system if you install as single user. Read the output of installer to check which files were modified.

Multi-User:

The rvm function will be automatically configured for every user on the system if you install with sudo. This is accomplished by loading /etc/profile.d/rvm.sh on login. Most Linux distributions default to parsing /etc/profile which contains the logic to load all files residing in the /etc/profile.d/ directory. Once you have added the users you want to be able to use RVM to the rvm group, those users MUST log out and back in to gain rvm group membership because group memberships are only evaluated by the operating system at initial login time. Zsh not always sources /etc/profile so you might need to add this in /etc/**/zprofile :

Mixed mode (user gemsets):

  • After following above instructions for Multi-User.
  • Select a user as a manager — he will be responsible for installing new rubies. This user should never run the command introduced below. If this happens, remove/rename the $/.rvmrc , logout and then relogin. Otherwise you won’t be able to install/upgrade new rubies correctly.

For each user that want to use RVM, an additional command needs to be run (once) for each user:

Gemsets created by these users will be hosted in their HOME directory. It’s not possible to use global gemsets from system without using tricks like manually linking directories and they should not be used in mixed-mode. Please bear in mind that ‘system’ in this context does not refer to your distribution’s ruby packages, but to the RVM Multi-User installation.

You have two possibilities to manage RVM. The first one is to add managers to the rvm group. The second one is to use separate managers with rvmsudo and privilege escalation. Note that it is not safe to use rvmsudo from mixed mode user. Both can be mixed without any side-effect. It is however very important to not enable mixed-mode gemsets or rubies for the managers. RVM is using a custom umask ( umask u=rwx,g=rwx,o=rx ) when installing gemsets, rubies, updating itself, etc. This should not impact your system. But if you prefer to avoid RVM messing around with your umask, you can comment the umask line in /etc/rvmrc .

This mode should also works with passenger, please follow passenger instructions. .

∞3. Reload shell configuration & test

Close out your current shell or terminal session and open a new one (preferred). You may load RVM with the following command:

If installation and configuration were successful, RVM should now load whenever you open a new shell. This can be tested by executing the following command which should output rvm is a function as shown below.

NOTE: Before reporting problems check rvm notes as it might contain important information.

Congratulations! You have successfully installed RVM.

∞Try out your new RVM installation

Below are some examples of how to install and use a Ruby under RVM.

Display a list of all known rubies. NOTE: RVM can install many more Rubies not listed.

Install a version of Ruby (eg 2.1.1 ):

Use the newly installed Ruby:

Check this worked correctly:

Optionally, you can set a version of Ruby to use as the default for new shells. Note that this overrides the ‘system’ ruby:

∞Enjoy using RVM!

∞Where to now?

If you are new to RVM I recommend that you read the basics page. At the end of the basics page there are further links for getting started.

∞Troubleshooting Your Install

and got the notice

ca-certificates need to be installed:

If you open a new shell and running:

does not show rvm is a function , RVM isn’t being sourced correctly.

Ensure that RVM is sourced after any path settings as RVM manipulates the path. If you don’t do this, RVM may not work as expected.

If you are using GNOME on Red Hat, CentOS or Fedora, ensure that the Run command as login shell option is checked under the Title and Command tab in Profile Preferences. After changing this setting, you may need to exit your console session and start a new one before the changes take affect.

Установка Ruby и настройка локальной среды разработки в Windows 10

Ruby – это динамический язык программирования, в котором можно написать что угодно: от простых скриптов до игр и веб-приложений. Ruby появился в Японии в 1993 году, но только в 2005 году он стал популярным языком для разработки на стороне сервера. Ruby прост в использовании и с ним легко работать даже новичкам, но он достаточно мощный, чтобы создавать сложные системы. Это отличный выбор для начинающих и опытных разработчиков.

Существует много способов установки Ruby в Windows. Microsoft рекомендует использовать для разработки Ruby Windows Subsystem for Linux (WSL) и Bash. WSL – это функция Windows 10, которая позволяет запускать инструменты командной строки Linux в Windows. Многие библиотеки Ruby предназначены для работы в Linux, и при использовании их в Windows могут возникать проблемы. Компания Microsoft сотрудничает с Linux, чтобы разрешить встроенную поддержку оболочки Bash и инструментов командной строки Linux для решения проблем совместимости Ruby и Windows. Установив Bash и WSL, вы сможете редактировать файлы с помощью инструментов Windows, а для работы Ruby и связанных с ним библиотек использовать Bash.

Данное руководство научит настраивать среду разработки Ruby на локальной машине Windows с помощью командной строки. Для тестирования среды будет создана простая программа Ruby.

Требования

  • Машина Windows 10.
  • Creators Update.
  • Права администратора.

1: Установка Bash в Windows

Для установки Ruby будет использована командная строка. Командная строка представляет собой неграфический способ взаимодействия с компьютером. Вместо нажатия кнопок с помощью мыши вы вводите команды в виде текста и получаете обратную связь опять же в виде текста. Командная строка, также известная как оболочка, позволяет вам автоматизировать многие рутинные задачи и является важным инструментом для разработчиков программного обеспечения.

Windows предлагает два интерфейса командной строки «из коробки»: классическую командную строку и PowerShell. Для работы с Ruby рекомендуется установить строку Bash, популярный командный язык, которые используется в Linux и macOS.

Включите на машине Developer mode. Для этого откройте Settings, выберите Update & Security, в боковой панели найдите For developers. Затем выберите опцию Developer mode и подтвердите изменения.

Откройте Control Panel и выберите Programs → Turn Windows features on or off. В списке компонентов выберите опцию Windows Subsystem For Linux (Beta). Кликните OK и подождите, пока система установит дополнительные компоненты. Это может занять несколько минут.

После этого система предложит перезапустить компьютер. Сделайте это, чтобы обновить общесистемные файлы.

После перезагрузки откройте командную строку и введите:

Будет предложено установить Bash из Windows Store. Это бесплатно, загрузка занимает несколько минут.

This will install Ubuntu on Windows, distributed by Canonical
and licensed under its terms available here:
https://aka.ms/uowterms
Press «y» to continue: y
Downloading from the Windows Store. 100%
Extracting filesystem, this will take a few minutes.

После установки инсталлятор предложит создать пользователя:

Please create a default UNIX user account. The username does not need to match your Windows username.
For more information visit: https://aka.ms.wslusers
Enter new UNIX username: 8host
Enter new UNIX password:

Укажите имя пользователя, нажмите Enter, введите пароль.

При вводе пароля символы не отображаются в окне терминала. Эта мера безопасности часто применяется при запросе паролей в командной строке. Вы не будете видеть символов, но система все равно будет фиксировать нажимаемые клавиши. Введите пароль и нажмите Enter, чтобы продолжить.

Оболочка Bash запустится. Командная строка будет выглядеть так:

Важно! Windows Subsystem for Linux имеет собственную файловую систему, которая хранится в скрытом файле в операционной системе. Microsoft не поддерживает доступ приложений Windows к этой файловой системе.

Однако все существующие файлы доступны в оболочке Bash. Например, все содержимое диска C можно найти в каталоге /mnt/c. Корпорация Microsoft рекомендует работать с файлами из этой папки. Таким образом, вы можете использовать инструменты Windows для работы с файлами и по-прежнему обращаться к ним из оболочки Bash. Доступ к файлам из других частей Windows Subsystem for Linux через программы Windows, таких как текстовые редакторы, файловые менеджеры и IDE, может привести к повреждению данных и не поддерживается.

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

RVM автоматизирует процесс установки среды Ruby в системе Ubuntu, на которой основана ваша установка Bash.

Самый быстрый способ установить Ruby с помощью RVM – запустить сценарий установки, размещенный на веб-сайте RVM.

Сначала используйте команду gpg, чтобы связаться с сервером открытых ключей и запросить ключ проекта RVM, который используется для подписи каждой версии RVM. Это позволяет подтвердить подлинность релиза RVM. В домашнем каталоге выполните следующую команду:

gpg —keyserver hkp://keys.gnupg.net —recv-keys 409B6B1796C275462A1703113804BB82D39DC0E3 7D2BAF1CF37B13E2069D6956105BD0E739499BDB

Затем установите пакет gnupg2 (сценарий установки RVM будет использовать компоненты этого пакета для проверки релиза). Выполните эту команду:

sudo apt-get install gnupg2

Для установки программы нужно ввести пароль администратора. Однако при вводе пароля символы не отображаются в окне терминала. Эта мера безопасности часто применяется при запросе паролей в командной строке. Вы не будете видеть символов, но система все равно будет фиксировать нажимаемые клавиши. Введите пароль, нажмите Enter и программа будет установлена.

Затем используйте команду curl для загрузки сценария установки RVM с веб-сайта проекта. Обратный слеш в начале команды отключает все псевдонимы команды и запускает обычную команду curl.

\curl -sSL https://get.rvm.io -o rvm.sh

В команде использованы такие флаги:

  • Флаг -s (–silent) отключает индикатор выполнения.
  • Флаг -S (–show-error) включает поддержку сообщений об ошибках curl.
  • Флаг -L (–location) включает обработку редиректов. Если сервер сообщает, что запрошенная страница переместилась на другой адрес, команда автоматически отправит запрос в новое местоположение.

После загрузки можно проверить содержимое сценария перед его запуском:

Используйте клавиши со стрелками для прокрутки файла. Чтобы вернуться в командную строку, нажмите q.

Убедившись, что сценарий не содержит ничего лишнего, выполните эту команду, чтобы установить последнюю стабильную версию RVM:

cat rvm.sh | bash -s stable

Сценарий создает в домашнем каталоге новый каталог под названием .rvm. Здесь будет установлен релиз Ruby и все связанные с ним компоненты, а также исполняемая программа rvm, которую вы используете для установки Ruby. Процесс установки изменит файл.bashrc и добавит папку .rvm/bin в переменную среды PATH. Это позволит запускать команду rvm.

Однако в текущей сессии команда rvm будет недоступна. Чтобы исправить это, введите:

Используйте rvm, чтобы установить последнюю версию Ruby.

rvm install ruby —default

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

Searching for binary rubies, this might take some time.
Found remote file https://rvm_io.global.ssl.fastly.net/binaries/ubuntu/16.04/x86_64/ruby-2.4.0.tar.bz2

Если в системе не хватает важных зависимостей, инсталлятор загрузит и установит их. При этом он может запросить пароль пользователя Linux.

Checking requirements for ubuntu.
Installing requirements for ubuntu.
Updating system.
Installing required packages: gawk, libssl-dev, zlib1g-dev, libyaml-dev, libsqlite3-dev, sqlite3, autoconf, libgmp-dev, libgdbm-dev, libncurses5-dev, automake, libtool, bison, libffi-dev, libgmp-dev, libreadline6-dev.
Requirements installation successful.

Установив зависимости, RVM загрузит и установит Ruby.

ruby-2.4.0 — #configure
ruby-2.4.0 — #download
% Total % Received % Xferd Average Speed Time Time Time Current
Dload Upload Total Spent Left Speed
100 16.4M 100 16.4M 0 0 4828k 0 0:00:03 0:00:03 —:—:— 4829k
ruby-2.4.0 — #validate archive
ruby-2.4.0 — #extract
ruby-2.4.0 — #validate binary
ruby-2.4.0 — #setup
ruby-2.4.0 — #gemset created /home/brian/.rvm/gems/ruby-2.4.0@global
ruby-2.4.0 — #importing gemset /home/brian/.rvm/gemsets/global.gems.
ruby-2.4.0 — #generating global wrappers.
ruby-2.4.0 — #gemset created /home/brian/.rvm/gems/ruby-2.4.0
ruby-2.4.0 — #importing gemsetfile /home/brian/.rvm/gemsets/default.gems evaluated to empty gem list
ruby-2.4.0 — #generating default wrappers.

После выполнения сценария будет установлена последняя версия Ruby.

В дополнение к Ruby RVM устанавливает несколько сопутствующих инструментов: irb (интерактивная консоль Ruby), rake (программа для запуска сценариев автоматизации) и gem (упрощает установку и обновление библиотек Ruby, которые можно использовать в проектах).

Запросите версию Ruby:

ruby -v
ruby 2.4.0p0 (2016-12-24 revision 57164) [x86_64-linux]

Важно! Чтобы менеджер RVM мог использовать эту версию Ruby при запуске сессий Bash, нужно запустить Bash как login shell. RVM нужен доступ к файлу .bash_profile, который вызывается только в login shell. Bash for Windows не запускает login shell по умолчанию, потому для работы с Ruby нужно открыть командную строку и запустить Bash с помощью команды:

Также вместо этого можно запускать следующую команду при каждом запуске Bash:

3: Создание простой программы Ruby

Чтобы убедиться, что среда работает, напишите простую программу «Hello, World».

Создайте файл hello.rb:

Введите в него следующий код:

puts «Hello, World!»

Нажмите Y, чтобы сохранить файл.

Программа выведет на экран следующую фразу:

Эта простая программа подтверждает, что среда разработки настроена правильно.

Теперь локальная машина готова к разработке программного обеспечения.

Вы можете использовать эту среду для изучения Ruby и создания более сложных и интересных проектов.

Читайте также:  Зациклилась обновление windows 10
Оцените статью