- How To Install Ruby on Rails with rbenv on Ubuntu 20.04
- Prerequisites
- Step 1 – Install rbenv and Dependencies
- Step 2 – Installing Ruby with ruby-build
- Step 3 – Working with Gems
- Step 4 – Installing Rails
- Step 5 – Updating rbenv
- Step 6 – Uninstalling Ruby versions
- Step 7 – Uninstalling rbenv
- Conclusion
- Ruby: установка и управление gem в Ruby
- Leave a Reply Cancel reply
How To Install Ruby on Rails with rbenv on Ubuntu 20.04
Ruby on Rails is one of the most popular application stacks for developers looking to create sites and web apps. The Ruby programming language, combined with the Rails development framework, allows you to build and deploy scalable apps quickly.
You can install Ruby and Rails with the command line tool rbenv. Using rbenv provides you with a solid environment for developing your Ruby on Rails applications and allows you to switch between Ruby versions, keeping your entire team on the same version. rbenv also provides support for specifying application-specific versions of Ruby, allows you to change the global Ruby for each user, and the option to use an environment variable to override the Ruby version.
In this tutorial, we will guide you through the Ruby and Rails installation processes with rbenv and gem . First, you’ll install the appropriate packages to install rbenv and then Ruby. After, you’ll install the ruby-build plugin so that you can install available versions of Ruby. Last, you’ll use gem to install Rails and can then use Ruby on Rails to begin your web development. We will also provide steps on how to check if your rbenv version is up-to-date, and how to uninstall Ruby versions and rbenv.
Prerequisites
To follow this tutorial, you need:
- One Ubuntu 20.04 server set up by following the Ubuntu 20.04 initial server setup guide, including a sudo non-root user and a firewall.
- Node.js installed using the official PPA, as explained in option 2 of How To Install Node.js on Ubuntu 20.04. A few Rails features, such as the Asset Pipeline, depend on a JavaScript Runtime. Node.js provides this functionality.
Step 1 – Install rbenv and Dependencies
Ruby relies on several packages that you can install through your package manager. Once those are installed, you can install rbenv and use it to install Ruby.
First, update your package list:
Next, install the dependencies required to install Ruby:
- sudoaptinstallgitcurl libssl-dev libreadline-dev zlib1g-dev autoconf bison build-essential libyaml-dev libreadline-dev libncurses5-dev libffi-dev libgdbm-dev
After installing the dependencies, you can install rbenv itself. Use curl to fetch the install script from Github and pipe it directly to bash to run the installer:
Next, add ~/.rbenv/bin to your $PATH so that you can use the rbenv command line utility. Do this by altering your ~/.bashrc file so that it affects future login sessions:
Then, add the command eval «$(rbenv init -)» to your ~/.bashrc file so rbenv loads automatically:
Next, apply the changes you made to your ~/.bashrc file to your current shell session:
Verify that rbenv is set up properly by running the type command, which will display more information about the rbenv command:
Your terminal window will display the following:
Outputrbenv is a function rbenv () < local command; command="$"; if [ "$#" -gt 0 ]; then shift; fi; case "$command" in rehash | shell) eval "$(rbenv "sh-$command" "$@")" ;; *) command rbenv "$command" "$@" ;; esac >
At this point, you have both rbenv and ruby-build installed. Let’s install Ruby next.
Step 2 – Installing Ruby with ruby-build
With the ruby-build plugin now installed, you can install whatever versions of Ruby that you may need with a single command. First, list all the available versions of Ruby:
The output of that command will be a list of versions that you can choose to install:
Output2.6.8 2.7.4 3.0.2 jruby-9.2.19.0 mruby-3.0.0 rbx-5.0 truffleruby-21.2.0.1 truffleruby+graalvm-21.2.0 Only latest stable releases for each Ruby implementation are shown. Use 'rbenv install --list-all / -L' to show all local versions.
Now let’s install Ruby 2.7.6 :
Installing Ruby can be a lengthy process, so be prepared for the installation to take some time to complete.
Once it’s done installing, set it as your default version of Ruby with the global sub-command:
Verify that Ruby was properly installed by checking its version number:
If you installed version 2.7.6 of Ruby, this command will return output like this:
Outputruby 3.0.2p107 (2021-07-07 revision 0db68f0233) [x86_64-linux]
You now have at least one version of Ruby installed and have set your default Ruby version. Next, you will set up gems and Rails.
Step 3 – Working with Gems
Gems are the way Ruby libraries are distributed. You use the gem command to manage these gems, and use this command to install Rails.
When you install a gem, the installation process generates local documentation. This can add a significant amount of time to each gem’s installation process, so turn off local documentation generation by creating a file called ~/.gemrc which contains a configuration setting to turn off this feature:
Bundler is a tool that manages gem dependencies for projects. Install the Bundler gem next, as Rails depends on it:
You’ll receive the following output:
OutputFetching bundler-2.2.27.gem Successfully installed bundler-2.2.27 1 gem installed
You can use the gem env command (the subcommand env is short for environment ) to learn more about the environment and configuration of gems. You can confirm where gems are being installed by using the home argument, like this:
You’ll receive an output similar to this:
Output/home/sammy/.rbenv/versions/2.7.6/lib/ruby/gems/2.7.0
Once you have gems set up, you can install Rails.
Step 4 – Installing Rails
To install Rails, use the gem install command along with the -v flag to specify the version. For this tutorial, you’ll use version 6.1.4.1 :
The gem command installs the gem you specify, as well as any of its dependencies. Rails is a complex web development framework and has many dependencies, so the process will take some time to complete. Eventually, you’ll receive a message stating that Rails is installed, along with its dependencies:
Output. Successfully installed rails-6.1.4.1 37 gems installed
Note: If you would like to install a different version of Rails, you can list the valid versions of Rails by doing a search, which will output a list of possible versions. You can then install a specific version, such as 4.2.7 :
If you would like to install the latest version of Rails, run the command without a version specified:
rbenv works by creating a directory of shims, which point to the files used by the Ruby version that’s currently enabled. Through the rehash sub-command, rbenv maintains shims in that directory to match every Ruby command across every installed version of Ruby on your server. Whenever you install a new version of Ruby or a gem that provides commands as Rails does, you should run the following:
Verify that Rails has been installed properly by printing its version, with the following command:
If it’s installed properly, this command will return the version of Rails that was installed:
At this point, you can begin testing your Ruby on Rails installation and start to develop web applications. Now let’s review how to keep the rbenv up-to-date.
Step 5 – Updating rbenv
Since you installed rbenv manually using Git, you can upgrade your installation to the most recent version at any time by using the git pull command in the ~/.rbenv directory:
This will ensure that you are using the most up-to-date version of rbenv available.
Step 6 – Uninstalling Ruby versions
As you download additional versions of Ruby, you may accumulate more versions than you would like in your ~/.rbenv/versions directory. Use the ruby-build plugin’s uninstall subcommand to remove these previous versions.
The following command will uninstall Ruby version 2.7.6 :
With the rbenv uninstall command you can clean up old versions of Ruby so that you do not have more installed than you are currently using.
Step 7 – Uninstalling rbenv
If you’ve decided you no longer want to use rbenv, you can remove it from your system.
To do this, first open your ~/.bashrc file in your editor. In this example, we will use nano :
Find and remove the following two lines from the file:
. export PATH="$HOME/.rbenv/bin:$PATH" eval "$(rbenv init -)"
After removing these lines, save the file and exit the editor. If you used nano , you can exit by pressing CTRL + X then Y and ENTER .
Then remove rbenv and all installed Ruby versions with the following command:
Log out and back in to apply the changes to your shell.
Conclusion
In this tutorial, you installed rbenv and gem to install the entire Ruby on Rails framework. From here, you can begin creating your web development application projects. If you want to learn more about making those environments more robust you can check out our series on How To Code In Ruby.
Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.
Ruby: установка и управление gem в Ruby
Гемы обычно ставятся через утилиту gem – она заведует поиском/установкой/удалениями гемов и имеет другие полезные команды. Краткий ман. Утилита поддерживает мультиверсионность гемов – если последняя вышедшая версия используемого вами gem не совместима с той, которую вы используете сейчас, то можно использовать обе версии одновременно. Так же установить gem можно указав URL (часто в репозитории гемы не актуальны), но для этого нужно сначала скачать gem specific_install.
sudo gem install snmp/net-ping/builder/spreadsheet/mechanize # установка самой последней версии (RubyGems по умолчанию выберет последнюю) sudo gem install builder -v 1.1.0 # установка конкретной версии gem environment – куча инфы (версия руби и гемов, где лежит руби и гемы и прочее) sudo gem install specific_install # устанавливаем gem для возможности прямой установки по URL sudo gem specific_install https://github.com/telegram-bot-rb/telegram-bot.git # устанавливаем gem telegram_bot
Так же для установки могут использоваться собранные пакеты с гемами в стандартных репозиториях ОС. Способ хуже. Пригодно для установки только для популярных гемов, например в Gentoo такие гемы ставятся через emerge (-vp проверяем отсутствие конфликтов с опцией pretend, -v – устанавливаем). Точные названия можно посмотреть на gentoo.org
sudo emerge -vp dev-ruby/mechanize sudo emerge -vp dev-ruby/ruby-oci8 sudo emerge -vp phantomjs
После установки gem, достаточно написать команду require, чтобы подключить его. Т.е. работа с гемами не отличается от работы с обычными библиотеками.
Если после этого пишет “no such file to load — ”, а gem при этом установлен локально – может помочь строчка require ‘rubygems’.
/home/redkin_p/bin/test.rb:6:in `require': no such file to load -- snmp (LoadError) from /home/redkin_p/bin/test.rb:6
gem list |snmp/builder| # список гемов gem list --remote # показывает все хдоступые гемах в репозитории, а не локально (как без опции) gem list --remote --name-matches net-ping # ищем конкретный гем sudo gem uninstall net-ping # удаление GEM sudo gem cleanup rjb # удаление старых версий sudo gem uninstall telegram-bot-ruby --version 0.8.6.1 # удаление определенной версии gem environment # тут можно посмотреть много разной инфы. К примеру очень полезен путь до гемов, исполняемый ruby
Пример разбора ошибок установки gem из-за системных библиотек и других зависимых gem есть в статье про mechanize.
Если Ruby установлен через RVM:
rvm 2.4.0 # переходим в RVM gem install unicode # ставим gem
Leave a Reply Cancel reply
You must be logged in to post a comment.