Установить gem на windows

Last Updated :
03 Sep, 2024

RubyGems is a Ruby package manager that provides Ruby programs and libraries (also known as Gems) and the tools associated with installing and managing Ruby packages and servers. The Ruby package management, RubyGems, makes it simple to install, manage, and utilize tools and libraries for Ruby applications. It is imperative to have RubyGems installed if you are using Ruby for development on a Windows PC.

In this article, we will look into the process of installing RubyGems on Windows.

Prerequisites

Make sure your machine satisfies the following prerequisites before you start:

  • Windows 10 or later: Although this tutorial is designed specifically for Windows 10, it should also function with earlier versions.
  • Ruby: Since RubyGems comes pre-loaded with Ruby, your machine must have Ruby installed.

Installing RubyGems on Windows:

Follow the below steps to install RubyGems on Windows:

Step 1: At first search, ruby download in your browser.

Step 2: Then Click on the Ruby installer for Windows.

Step 3: Then click on the Download Button.

Step 4: Then according to your operating system download your suitable one. For 64 bit download the following one

Step 5: Then click on the downloaded file. Then accept the license & click next.

Step 6: Then click on the Next button.

Step 7: Then we have to wait for some time to install.

Step 8: Then we have to go to the C drive of the computer. Then move to the Ruby 27-x64 folder. And then the bin folder. Then copy the path.

Step 9: Then we have to go to the environment variable.

environment variable

Step 10: Then we will move to the path & insert the copied path.

Step 11: Then after installing Ruby will open & we have to click Enter.

Step 12: After waiting some time again we have to click Enter. Then it will close.

Step 13: Then we will check it. We will open the command prompt. There we will type the following commands: 

ruby -v
ruby --version
gem -v

These will give the below-shown output:

Step 14: Then we will run a simple program. By writing the command ruby -e «puts ‘Hello World…'». In ruby puts means to print anything. This will generate Hello World

Conclusion

RubyGems installation on Windows is very simple, provided that Ruby is installed correctly. You may concentrate more on work and less on setup by using RubyGems to manage Ruby libraries and dependencies.

Also Read

  • How to Install Ruby gems offline?
  • How to Install RubyGems on Linux?
  • How to Install RubyGems on MacOS?

# Gems

In this example we will use ‘nokogiri’ as an example gem. ‘nokogiri’ can later on be replaced by any other gem name.

To work with gems we use a command line tool called gem followed by an option like install or update and then names of the gems we want to install, but that is not all.

Install gems:

But that is not the only thing we need. We can also specify version, source from which to install or search for gems. Lets start with some basic use cases (UC) and you can later on post request for an update.

Listing all the installed gems:

Uninstalling gems:

If we have more version of the nokogiri gem we will be prompted to specify which one we want to uninstall. We will get a list that is ordered and numbered and we just write the number.

Updating gems

or if we want to update them all

Comman gem has many more usages and options to be explored. For more please turn to the official documentation. If something is not clear post a request and I will add it.

# Installing Ruby macOS

So the good news is that Apple kindly includes a Ruby interpreter. Unfortunately, it tends not to be a recent version:

If you have Homebrew installed (opens new window), you can get the latest Ruby with:

(It’s likely you’ll see a more recent version if you try this.)

In order to pick up the brewed version without using the full path, you’ll want to add /usr/local/bin to the start of your $PATH environment variable:

Adding that line to ~/.bash_profile ensures that you will get this version after you restart your system:

Homebrew will install gem for installing Gems (opens new window). It’s also possible to build from the source (opens new window) if you need that. Homebrew also includes that option:

# Linux — Compiling from source

`This way you will get the newest ruby but it has its downsides. Doing it like this ruby will not be managed by any application.

!! Remember to chagne the version so it coresponds with your !!

  1. you need to download a tarball find a link on an official website (https://www.ruby-lang.org/en/downloads/) (opens new window))
  2. Extract the tarball
  3. Install

This will install ruby into /usr/local. If you are not happy with this location you can pass an argument to the ./configure --prefix=DIR where DIR is the directory you want to install ruby to.

# Linux—Installation using a package manager

Probably the easiest choice, but beware, the version is not always the newest one. Just open up terminal and type (depending on your distribution)

in Debian or Ubuntu using apt

in CentOS, openSUSE or Fedora

You can use the -y option so you are not prompted to agree with the installation but in my opinion it is a good practice to always check what is the package manager trying to install.

# Windows — Installation using installer

Probably the easies way to set up ruby on windows is to go to http://rubyinstaller.org/ (opens new window) and from there donwload an executable that you will install.

You don’t have to set almost anything, but there will be one important window. It will have a check box saying Add ruby executable to your PATH. Confirm that it is checked, if not check it or else you won’t be able to run ruby and will have to set the PATH variable on your own.

Then just go next until it installs and thats that.

# Linux — troubleshooting gem install

First UC in the example Gems $> gem install nokogiri can have a problem installing gems because we don’t have the permissions for it. This can be sorted out in more then just one way.

First UC solution a:

U can use sudo. This will install the gem for all the users. This method should be frowned upon. This should be used only with the gem you know will be usable by all the users. Usualy in real life you don’t want some user having access to sudo.

First UC solution b

U can use the option --user-install which installs the gems into your users gem folder (usualy at ~/.gem)

First UC solution c

U can set GEM_HOME and GEM_PATH wich then will make command gem install install all the gems to a folder which you specify. I can give you an example of that (the usual way)

  • First of all you need to open .bashrc. Use nano or your favorite text editor.
  • Then at the end of this file write
  • Now you will need to restart terminal or write . ~/.bashrc to re-load the configuration. This will enable you to use gem isntall nokogiri and it will install those gems in the folder you specified.

Вроде бы всё просто:

Что такое Jekyll — Jekyll.

Но ведь это Windows (Windows 7 в моём случае).

Нам понадобится chocolatey (аналог apt-get и homebrew).
Затем в командной строке

cinst ruby

cinst source ruby jekyll

Последняя команда выдаст ошибку, что нужно установить DevKit, вот описание установки: https://github.com/oneclick/rubyinstaller/wiki/Development-Kit, отсюда скачивать: http://rubyinstaller.org/downloads (я выбрал https://github.com/downloads/oneclick/rubyinstaller/DevKit-tdm-32-4.5.2-20111229-1559-sfx.exe и распаковал в c:\rubydevkit).

cd c:\rubydevkit

ruby dk.rb init

// при необходимости поправить конфиг в config.yml

ruby dk.rb install

И затем осталось только выполнить

cinst source ruby jekyll

Similar Posts

I Copied from the following URL:

1) http://rubyonwindowsguides.github.io/book/ch02-05.html

Now we are fully equipped for Ruby development on Windows. Yet problem of installing native gems requires our attention and better explanation. DevKit’s smoke test passed without problem but does it mean we can install any gem written in C/C++? Unfortunately the answer is no.

Native gems might depend on other libraries which are hard, or sometimes, impossible to build on Windows. Example of such a gem is Nokogiri, HTML and XML parser for Ruby, built upon Libxml2 library. Libxml2 is XML parser and toolkit written in C. If you want to know how to deal, at least partially, with such a libraries you should continue reading this chapter. Otherwise you can freely skip to the section “Installing Ruby On Rails”.

c:\>gem install nokogiri —platform=ruby

Temporarily enhancing PATH to include DevKit…

Building native extensions. This could take a while…

ERROR: Error installing nokogiri:

ERROR: Failed to build gem native extension.

C:/Ruby/192/bin/ruby.exe extconf.rb

checking for libxml/parser.h… no

——

libxml2 is missing. please visit http://nokogiri.org/tutorials/installing_nokogiri.html for help with

installing dependencies.

——

*** extconf.rb failed ***

Could not create Makefile due to some reason, probably lack of

necessary libraries and/or headers. Check the mkmf.log file for more

details. You may need configuration options.

Our attempt to install Nokogiri did not succeed due to a missing header file from Libxml2 library. This will happen whenever you try to install native gems that do not have pre-built binaries for Windows system and libraries that these gems depend on are not available.

However this problem is not inherent to Windows and Ruby. In order to install C/C++ Ruby extensions on each system you must have build tools and all dependencies installed. This means if you do not have Libxml2 installed on the Linux or OSX you will face exactly the same problem. The fact is that most of such gems are developed primarily on Linux where developers, naturally, rely on existing libraries. On the other hand lot of these libraries are portable and can be used on Windows, but number of them are shipped in a binary format because building them on Windows is quite complicated.

But it is not all that bad as it looks on the first sight. The fact is that at a time of One-Click Ruby Installer which was built with Visual Studio it was very hard to build external libraries and gems. Moreover Visual Studio was commercial and not all of Ruby developers had it. RubyInstaller project has changed a lot in that field. MRI itself depends on some libraries like libYAML and LibFFI but both of them were built when we were installing Ruby from sources. Moving the whole Ruby build procedure to MSYS/MinGW tool chain was a big step which resulted in possibility to use external libraries built with same compiler tools. This lead to much bigger set of native gems that became available to Ruby developers on Windows.

We will walk through the complete procedure of installing one native gem altogether with its external dependency. The gem is Ruby interface for sqlite3 database. First we will try to install gem from sources as we did with Nokogiri

C:\>gem install sqlite3 –platform=ruby

Temporarily enhancing PATH to include DevKit…

Building native extensions. This could take a while…

ERROR: Error installing sqlite3:

ERROR: Failed to build gem native extension.

C:/Ruby/192/bin/ruby.exe extconf.rb

checking for sqlite3.h… no

sqlite3.h is missing. Try ‘port install sqlite3 +universal’

or ‘yum install sqlite3-devel’ and check your shared library search path (the

location where your sqlite3 shared library is located).

*** extconf.rb failed ***

Could not create Makefile due to some reason, probably lack of

necessary libraries and/or headers. Check the mkmf.log file for more

details. You may need configuration options.

Provided configuration options:

—with-opt-dir

—without-opt-dir

—with-opt-include

—without-opt-include=${opt-dir}/include

—with-opt-lib

—without-opt-lib=${opt-dir}/lib

—with-make-prog

—without-make-prog

—srcdir=.

—curdir

—ruby=C:/Ruby/192/bin/ruby

—with-sqlite3-dir

—without-sqlite3-dir

—with-sqlite3-include

—without-sqlite3-include=${sqlite3-dir}/include

—with-sqlite3-lib

—without-sqlite3-lib=${sqlite3-dir}/lib

Gem files will remain installed in C:/Ruby/192/lib/ruby/gems/1.9.1/gems/sqlite3-1.3.3 for inspection.

Results logged to C:/Ruby/192/lib/ruby/gems/1.9.1/gems/sqlite3-1.3.3/ext/sqlite3/gem_make.out

This time we are displaying complete output of gem install command because we will completely analyze it. We see that script extconf.rb is executed at the beginning of the installation procedure. This is simple program that checks for prerequisites needed for the extension to be built. If all goes well Makefile is created. But something went wrong – C header file sqlite3.h was not found, script has printed out information and exited. If you check content of extconf.rb you will easily find the line responsible for premature script exit.

asplode(‘sqlite3.h’) unless find_header ‘sqlite3.h’

Function find_header, defined in Ruby’s mkmf module that creates Makefile, obviously returned false. Question is where it was looking for sqlite3.h file? The answer can be found in mkmf.log file which was created during this installation. Leaving out irrelevant parts here is the answer:

gcc -o conftest -IC:/Ruby/192/include/ruby-1.9.1/i386-mingw32 -IC:/Ruby/192/include/ruby-1.9.1/ruby/backward \

-IC:/Ruby/192/include/ruby-1.9.1 -I. -I/usr/local/include -I/opt/local/include \

-I/sw/local/include -I/usr/include

We can see several -I… sequences which tell GCC compiler where to search header files. First three directories are related to our Ruby (1.9.2), the fourth is current directory, followed by paths where header files are usually kept on Linux systems. But we are on Windows! Why does mkmf module uses these paths? Well, just one more proof that Ruby was in earlier days mostly oriented to Linux. But there is another, more logical, reason although it still favors Linux. Short explanation is that Linux File System Structure (FSS) defines structure of directories and where different type of files should be stored. Even though it is not obligatory for anyone, most of Linux versions today try to follow it, sometimes with neglecting modifications. According to FSS, header files should be in the /usr/local/include, /opt/local/include or /usr/include directories.

Windows operating system doesn’t have such specification which makes it impossible to use some predefined paths for searching header files. Besides, Windows doesn’t come with any development tool thus no header file exists on the system after installation. Despite FSS even on Linux some header files might be found in unusual places and you can pass additional paths that will be searched.

After this short digression let’s get back to the output we got when we tried to install sqlite3 gem. Script implied that we might need to use some configuration option and gave us a list of available options. End of list is obviously related to SQlite3 and if you look carefully you will find the one that might help us with missing header file, —with-sqlite3-include. If we pass a path where sqlite3 folder is with this option, configuration script will search it too and this might solve our problem.

Download file containing amalgamation for SQlite 3.7.4 with configure script from https://github.com/dlamichhane/sqlite3-amalgamation and place it to the c:\projects directory where we keep all sources. After extracting, our sqlite3.h file will be in the sqlite-autoconf-3070400 directory and full path to it is exactly what we have to pass to the configuration script. Go to the folder where Rubygems have left sqlite3 gem’s files, c:\Ruby\192\lib\ruby\gems\1.9.1\gems\sqlite3-1.3.3 and execute following statement:

ruby setup.rb config — —with-sqlite3-include=c:\projects\sqlite3

Notice two things. We passed config command to the setup.rb script, followed by two dashes surrounded by spaces and configuration option for adding new directory that will be searched for header files. Be careful. Without — above command will not work. And result is – failure again:

checking for sqlite3.h… yes

checking for sqlite3_libversion_number() in -lsqlite3… no

….

Configuration script has found header file but now it looks for function libversion_number() in -lsqlite3. Does this ring a bell? And if you substitute -l with lib? You are right! Configuration script tries to find function in the library. Passing libraries which GCC linker should use when it links executable or shared library is done by prefixing library name by -l. Linker will, in our case, search for a libsqlite3 library. If you look in the sqlite3 folder you will see that there is no file with that name there. That’s because we haven’t built SQlite3. We have just downloaded and extracted sources.

Let’s do it now. In order to that we must, in the current Command Prompt, add DevKit to the path, then start MSYS shell, configure SQlite3 and finally build it. SQlite3 README file suggests we should define SQLITE_ENABLE_COLUMN_METADATA when we build SQlite3. Let’s do all this now:

c:\projects\sqlite3>c:\Ruby\DevKit\devkitvars.bat

Adding the DevKit to PATH…

c:\projects\sqlite3>sh

sh-3.1$./configure CFLAGS=»-DSQLITE_ENABLE_COLUMN_METADATA»

c:\projects\sqlite3>make

Over here if you restart the command prompt, be sure to rerun the code ‘c:\Ruby\DevKit\devkitvars.bat’ again. And also copy the libsqlite3-0.dll and sqlite3 application file from the c:\projects\sqlite3\.libs to the C:\Ruby\Ruby2.0.0\bin. Make sure your sqlite3 application file works fine

When make command finishes check directory where SQlite3 sources were extracted. You will see new sub-directory .libs with several files in it. The most important to us are libsqlite3.dll.a (link library used for linking against SQlite3) and libsqlite3-0.dll (shared library used in run-time). Finally we have everything for building sqlite3 gem. Go to the sqlite3 gem folder and run following statements:

ruby setup.rb config — —with-sqlite3-include=c:\projects\sqlite3

–with-sqlite3-lib=C:\projects\sqlite3\.libs

ruby setup.rb setup

As a result you will get C extension used by this gem. Let’s check list of installed gems:

C:\>gem list

*** LOCAL GEMS ***

minitest (1.6.0)

pik (0.2.8)

rake (0.8.7)

rdiscount (1.6.8)

rdoc (2.5.8)

Our sqlite3 isn’t here! Well what we really did is that we built C extension but there are two more steps to be done so Rubygems are aware of sqlite3 gem existence. We must extract gem specification from the downloaded gem and put it in the specifications directory. Go to Rubygems cache folder where all downloaded gems are saved c:\Ruby\192\lib\ruby\gems\1.9.1\cache and issue following command:

gem spec sqlite3-1.3.3.gem —ruby > ..\specifications\sqlite3-1.3.3.gemspec

gem list

*** LOCAL GEMS ***

minitest (1.6.0)

pik (0.2.8)

rake (0.8.7)

rdiscount (1.6.8)

rdoc (2.5.8)

sqlite3 (1.3.3)

Finally Rubygems see our newly built sqlite3 gem. But before you check whether gem is working or not, you must copy sqlite3_native.so shared library from ext\sqlite3 folder to lib\sqlite3 folder. Now start irb and try to load gem:

C:\>irb

irb(main):002:0> require ‘sqlite3’

=> true

irb(main):003:0>

HOPE IT WORKS FOR YOU!!!!!!HURRAY

SOME TROUBLESHOOTING

URL : https://github.com/oneclick/rubyinstaller/wiki/Troubleshooting

Заинтересовал меня Rails. Купил пару книг, прочитал… достаточно чтобы, зачесались руки и пришло время ставить сабж. И приступать… хотя бы к экспериментам.

Задача: поставить Rails под Windows 7 (не спрашивайте меня почему) и запустить сервер.

Оказалось — это квест. Пары щелчков мышью недостаточно. Конечно, если не использовать Railsinstaller, на что мне правильно намекнули в комментариях (спасибо, dreamfall).

Несколько же часов моих поисков, завершившихся таки полной и безоговорочной инсталляцией, под катом.

1. Ставим Ruby. Строго отсюда rubyinstaller.org/downloads. Ибо тут он собран под gcc MinGW 32, который будет использоваться и для сборки ruby-модулей
1.1 Нам понадобиться версия 187. Версия 192 треует более мощного шаманства, на которое у меня маны не хватило.
1.2 Ставим Development Kit (он нам понадобиться, чтобы собрать Rails), распаковывая прямо поверх каталога Ruby (если ставили по умолчанию — это C:\Ruby187, в дальнейшем обзовем его $Ruby)
1.3 Можно заодно и документацию по Ruby скачать

2. Нам понадобиться SQLite www.sqlite.org. Архив c dll-кой и def файлом распаковываем прямо в каталог $Ruby\bin. Это кстати был первый сюрприз (раньше RDBMS «по умолчанию» был mySQL)

3. Запускаем Comand Prompt wiht Ruby (вы найдете его в start-меню windows)

4. В comand prompt ставим модули:
4.1. gem install sqlite3-ruby — SQLite
4.2. gem install rails — собственно сами «рельсы». Возможно, что установка прервется с ошибкой, в этом случае повторяем команду
4.3. Даже если ошибки не случилось, всё равно потребуется шаманство. Ибо, на каждый наш чих, будет вылезать вот такое непотребство:
Invalid gemspec in [C:/Ruby187/lib/ruby/gems/1.8/specifications/json-1.6.1.gemspec]: invalid date format in specification: «2011-09-18 00:00:00.000000000Z».
Это ошибка связанная с форматом даты. Лечится просто. Переходим в каталог $Ruby\lib\ruby\gems\1.8\specifications и в файлах «с ошибкой» меняем строчку
s.date = %q{2011-09-18 00:00:00.000000000Z}
на
s.date = %q{2011-09-18}
4.4. Для успокоения совести gem update rails —include-dependencies

5. Создаем тестовое приложение. Там же, в Command prompt
5.1 Переходим в каталог «для игр» например cd \test (или mkdir \test;cd \test — если такого каталога нет)
5.2 Создаем приложение rails new hello. Второй сюрприз — в книжках ничего не говорилось про «new».
5.3 Запускаем наше приложение. cd hello; rails server . И последний сюрприз — в тех же книжках ссылка на несуществующий больше скрипт rails server/script
5.4 по адресу localhost:3000

внезапно

мы обнаруживаем наше долгожданное приложение.

Вуаля!

Продолжение воспоследует, если по мере углубления обнаружатся еще подводные камни.

Если эта публикация вас вдохновила и вы хотите поддержать автора — не стесняйтесь нажать на кнопку

Понравилась статья? Поделить с друзьями:
0 0 голоса
Рейтинг статьи
Подписаться
Уведомить о
guest

0 комментариев
Старые
Новые Популярные
Межтекстовые Отзывы
Посмотреть все комментарии
  • Как восстановить office после восстановления windows
  • Зеркалит тачскрин на планшете windows
  • Как открыть папку local в windows 10
  • Как поставить видео обои на экран блокировки windows 10
  • Как настроить мышь в linux как в windows