- Ruby on Rails
- Contents
- Installation
- RubyGems
- Pacman
- Quarry binary repository
- Configuration
- Application servers
- Unicorn
- Systemd service
- Nginx Configuration
- Apache/Nginx (using Phusion Passenger)
- Puma (with Nginx as reverse proxy server)
- Option A: With config file
- Option 2: by systemd
- Databases
- SQLite
- PostgreSQL
- MySQL
- Database Access Configuration
- Create the databases from Rails
- The Perfect Rails Setup
- Step 0: SQLite
- Step 1: RVM
- Step 2: Rubies
- Step 3: Nginx with Passenger support
- Step 4: Gemsets and Apps
- Passenger for Nginx and Passenger Standalone
- Step 5: .rvmrc files and ownerships
- Step 6: Reverse proxies
- Launch Passenger Standalone daemons at system start-up
- Ruby on Rails на русском
- Установка RoR для Linux
- Установка RoR для Linux
Ruby on Rails
Ruby on Rails, often shortened to Rails or RoR, is an open source web application framework for the Ruby programming language. It is intended to be used with an Agile development methodology that is used by web developers for rapid development.
This document describes how to set up the Ruby on Rails Framework on an Arch Linux system.
Contents
Installation
Ruby on Rails requires Ruby to be installed, so read that article first for installation instructions. The nodejs package is also required if using uglifier (Ruby wrapper for UglifyJS JavaScript compressor, optional) The Rails framework is linked to a version of Ruby (or the system Ruby installation). Ruby version(s) installed can be from system or from rbenv or from rvm (Ruby Version Manager).
RubyGems
The following command will install Rails for the current user:
Building the documentation takes a while. If you want to skip it, append —no-document to the install command.
gem is a package manager for Ruby modules, somewhat like pacman is to Arch Linux. To update your gems, simply run:
Pacman
Quarry binary repository
Install ruby-rails from the unofficial quarry repository.
Configuration
Rails is bundled with a basic HTTP server called Puma. You can create a test application to test it. First, create an application with the rails command:
This creates a new folder inside your current working directory.
Next start the web server. It listens on port 3000 by default:
Now visit the testapp_name website on your local machine by opening http://localhost:3000 in your browser
A test-page should be shown greeting you «Welcome aboard».
Application servers
The built-in Ruby On Rails HTTP server (called Puma) is convenient for basic development, but it is not recommended for production use. Instead, you should use an application server such as #Thin, #Unicorn or Phusion Passenger.
Thin is a fast and very simple Ruby web server.
First install thin gem:
Then start it using:
Unicorn
Unicorn is an application server that cannot talk directly to clients. Instead, a web server must sit between clients and Unicorn, proxying requests as needed. Unicorn is loosely based on Mongrel. It is used by Github, and it uses an architecture that tries hard to find the best child for handling a request. Explanation of differences between Unicorn and Mongrel.
Install the Unicorn gem:
Then create a configuration file for your application in /etc/unicorn/ . For example; here is a configuration example based on this tutorial for Redmine:
Systemd service
Put the following contents in /etc/systemd/system/unicorn.service :
You can now easily start and stop unicorn using systemctl
Nginx Configuration
After setting up Nginx, configure unicorn as an upstream server using something like this (Warning: this is a stripped example. It probably does not work without additional configuration):
Apache/Nginx (using Phusion Passenger)
Phusion Passenger is a module available for Nginx and Apache HTTP Server, that greatly simplifies setting up a Rails server environment. Nginx does not support modules as Apache and has to be compiled with mod_rails in order to support Passenger; let Passenger compile it for you. As for Apache, let Passenger set up the module for you.
Two differents choices (one or the other, not both in same time):
- Install the passenger package.
- Installing the ‘passenger’ gem from any version of ruby (user setting):
If you are aiming to use Apache HTTP Server, install the mod_passenger package (if passenger is not installed from gem), and run:
In case a rails application is deployed with a sub-URI, like http://example.com/yourapplication, some additional configuration is required, see the Passenger documentation
For Nginx, install the nginx-mod-passenger package (if passenger is not installed from gem), and run:
The installer will provide you with any additional information regarding the installation (such as installing additional libraries).
To serve an application with Nginx, configure it as follows:
Puma (with Nginx as reverse proxy server)
Puma (Github Page) is a simple, fast, threaded, and highly concurrent HTTP 1.1 server for Ruby/Rack applications, and is considered the replacement for Webrick and Mongrel. It was designed to be the go-to server for Rubinius, but also works well with JRuby and MRI. While reverse proxy server would acts as a load balancer that routes all external requests to a pool of web apps.
For a webserver it is better to use a server user and group, check Users and groups#Example adding a user, below use rails as user name and server as group name, also my_app as rails app name.
Start by copying your app to /var/www/my_app. And set new ownership with
and permission for user with
Then add puma gem in the Gemfile and install with
Also install nginx by pacman.
Under your app folder, create sockets, pid and log folder with
Backup nginx.conf with
Then create a new nginx.conf file with your favorite editor, copy codes below and modify as you like:
Start the nginx service.
There are several ways to start puma server, two ways are recommended below:
In common create file config/puma.rb , copy codes below and modify as you like:
Option A: With config file
Start server with
You can also run it in background with parameter -d and check with
when you want to kill it.
If you want to keep it after you log out, you can use
But if the system reboot, the process will still get lost.
Option 2: by systemd
Create a new systemd unit puma.service under
/.config/systemd/user/ and copy codes below
Hint: For ExecStart, if you have installed gem globally, you can change routes to /usr/local/bin/ in ExecStart.
Then start puma with
To enable puma system-widely: You need to store puma.service in /etc/systemd/system/ and modify it as below:
For further reading take a look at #References. Also, for easily deploying app in production mode, you can try capistrano
Databases
Most web applications will need to interact with some sort of database. ActiveRecord (the ORM used by Rails to provide database abstraction) supports several database vendors, the most popular of which are MySQL, SQLite, and PostgreSQL. And then you will have next to configure the file «config/database.yml» for Rails application web site able to connect on your database.
SQLite
SQLite is the default lightweight database for Ruby on Rails. To enable SQLite, simply install sqlite .
PostgreSQL
Install for Rails:
Or add the gem inside your Gemfile of your project, then use bundle.
create a new Rails web site:
MySQL
First, install and configure a MySQL server. Please refer to MariaDB on how to do this.
A gem with some native extensions is required, probably best installed as root:
You can generate a rails application configured for MySQL by using the -d parameter:
Database Access Configuration
What ever Database (MySQL or Postgresql or SQlite (the default one) you use, you then need to edit config/database.yml . Rails uses different databases for development, testing, production and other environments. Here is an example development configuration for MySQL running on localhost:
For safety reasons, it is a good practice to not directly put password (who will be no more secret) as clear text in a text file. Instead you can replace «my_secret_password’ by «‘ ‘» where MYSQL_PASSWD can be an environment variable exported from the user environment the server use (
/.zshrc depend of your choice and utility). Surrounding by «‘» searve in case of your password has some special chars like # or !, etc.
Create the databases from Rails
Note that you do not have to actually create the database using MySQL or Postgresql or Sqlite, as this can be done via Rails directly with:
For rails-4.X version:
For rails-5.X version:
If no errors are shown, then your database has been created and Rails can talk to your MySQL database.
The Perfect Rails Setup
This article or section needs language, wiki syntax or style improvements. See Help:Style for reference.
Phusion Passenger running multiple Ruby versions.
- Arch Linux: A simple, lightweight distribution. 😉
- Nginx: A fast and lightweight web server with a strong focus on high concurrency, performance and low memory usage.
- Passenger (a.k.a. mod_rails or mod_rack): Supports both Apache and Nginx web servers. It makes deployment of Ruby web applications, such as those built on Ruby on Rails web framework, a breeze.
- Ruby Version Manager (RVM): A command-line tool which allows you to easily install, manage, and work with multiple Ruby environments from interpreters to sets of gems. RVM lets you deploy each project with its own completely self-contained and dedicated environment —from the specific version of ruby, all the way down to the precise set of required gems to run your application—.
- SQLite: The default lightweight database for Ruby on Rails.
Step 0: SQLite
Step 1: RVM
Make a multi-user RVM installation as specified here.
In the ‘adding users to the rvm group’ step, do
http and nobody are the users related to Nginx and Passenger, respectively.
Step 2: Rubies
Once you have a working RVM installation in your hands, it is time to install the latest Ruby interpreter
Step 3: Nginx with Passenger support
Run the following to allow passenger install nginx:
The passenger gem will be put into the default gemset.
This will download the sources of Nginx, compile and install it for you. It will guide you through all the process. Note that the default location for Nginx will be /opt/nginx .
After completion, add the following two lines into the ‘http block’ at /opt/nginx/conf/nginx.conf that look like:
Step 4: Gemsets and Apps
This article or section is out of date.
For each Rails application you should have a gemset. Suppose that you want to try RefineryCMS against BrowserCMS, two open-source Content Management Systems based on Rails.
Install RefineryCMS first:
Deploy a RefineryCMS instance called refineria:
Install BrowserCMS in a different gemset:
Deploy a BrowserCMS instance called navegador:
Passenger for Nginx and Passenger Standalone
Observe that the passenger gem was installed three times and with different intentions; in the environments
The strategy is to combine Passenger for Nginx with Passenger Standalone. One must first identify the Ruby environment (interpreter plus gemset) that one uses the most; in this setup the Ruby interpreter and the default gemset were selected. One then proceeds with setting up Passenger for Nginx to use that environment (step 3).
- Applications within the chosen environment can be served as in Apache/Nginx (using Phusion Passenger), page up in this article.
- All applications that are to use a different Ruby version and/or gemset can be served separately through Passenger Standalone and hook into the main web server via a reverse proxy configuration (step 6).
Step 5: .rvmrc files and ownerships
This step is crucial for the correct behaviour of the setup. RVM seeks for .rvmrc files when changing folders; if it finds one, it reads it. In these files normally one stores a line like
so the specified environment is set at the entrance of applications’ root folder.
Create /srv/http/refineria/.rvmrc doing
, and /srv/http/navegador/.rvmrc with
You have to enter to both application root folders now, because every first time that RVM finds a .rvmrc it asks you if you trust the given file, consequently you must validate the two files you have just created.
These files aid the programs involved to find the correct gems.
Apart, if applications’ files and folders are not owned by the right user you will face database write-access problems. The use of rvmsudo produces root-owned archives when generated by Rails; in the other hand, nobody is the user for Passenger —if you have not changed it—: who will use and should posses them. Fix this doing
Step 6: Reverse proxies
You have to start the Passenger Standalone web servers for your applications. So, do
. The first time that you run a Passenger Standalone it will perform a minor installation.
Note that you are using unix domain sockets instead of the commonly-used TCP sockets; it turns out that unix domain are significantly faster than TCP sockets.
Launch Passenger Standalone daemons at system start-up
Do you have a script? Please post it here.
The systemd script below was made for a Typo blog I host at /srv/http/typo. It is located at /etc/systemd/system/passenger_typo.service. I set the Environment= tags (see «man systemd.exec») from the output of «rvm env». The only exception was PATH=, which I had to combine from my regular PATH and the output of rvm env.
Note: If you do not set the «WorkingDirectory=» variable to your application folder, passenger will fail to find your app and will subsequently shut itself down.
Источник
Ruby on Rails на русском
Еще один блог о веб-разработке
Установка RoR для Linux
Установка RoR для Linux
Установка Ruby on Rails.
В этом посте мы рассмотрим установку необходимого ПО:
- Ruby (интерпретатор языка)
- Rails (платформа для веб-приложений и зависимости)
- PhantomJS (поддержка безгласного веб-тестирования)
- Sublime Text (опциональный редактор текста)
Мы будем устанавливать оригинал Matz’а, интерпретатор Ruby MRI Interpreter, основанный на C. Это означает, что мы собираемся много компилировать на нашей платформе Linux.
Когда мы устанавливаем Ruby, мы принимаем решение сделать правильный фундамент. И, к счастью, если мы просто будем придерживаться одной версии и не будем часто прыгать между разными интерпретаторами, нам, вероятно, не придется касаться к этому слою в будущем. Однако нам нужно установить его для работы.
Менеджер установки определяет, какие gem’ы работают с версиями Ruby. Установку различных версий в разные моменты времени. Сейчас есть несколько менеджеров, которые вы можете установить, и есть два, скажем, ведущих. Есть и другие.
Есть rvm, который является более старым, более устоявшимся, но это супертяжелый менеджер. Он делает некоторые вещи в оболочке, о которых некоторые на самом деле не думают. Поэтому в среде разработки это может быть не идеальным выбором.
Rbenv является более легким по весу решением, и во многом он работает по более традиционному пути UNIX.
Ладно, перейдем на сайт Rails, нажмем на загрузку.
Они рекомендуют rbenv. Хорошо, выбор немного проще. И они ссылаются на GitHub Стивенсона, у которого есть реализация. Там нет всех инструкций, но есть неплохая часть.
Так что погуглив, я нашел хорошую статью от Митчелла Аттика, о том, как установить Ruby on Rails с rbenv на Ubuntu. Отлично.
Одна из первых вещей, которые мы собираемся сделать, заключается в том, что мы собираемся обновить существующие пакеты, которые находятся в системе. Это то, что мы должны сделать, прежде чем добавлять к ней новые пакеты.
Как вы знаете, Ubuntu использует apt-get в качестве менеджера пакетов, а Fedora использует yum.
Когда мы запускаем этот диспетчер пакетов, мы используем команду sudo, которой нужен пароль, и этот пароль будет действовать в течение определенного периода времени.
Затем мы установим Git. Мы собираемся использовать Git изначально, чтобы клонировать репозитории rbenv и Ruby build.
И, конечно, он понадобится нам также в будущем.
На обоих системах это займет около пары минут до завершения.
Затем мы установим компилятор и некоторые из библиотек, которые он будет использовать для создания Ruby и различных gem’ов, которые есть там.
Данная установка занимает около нескольких минут.
Затем у нас есть две очень похожие операции на обеих платформах. Мы собираемся клонировать/устанавливать репозиторий rbenv.
Мы собираемся поместить его в папку прямо под home.
Клон был помещен в папку под home, и мы будем использовать переменные, чтобы указать на это местоположение.
Пока мы говорим о переменных среды, позвольте сделать небольшое отступление, чтобы описать, что они из себя представляют.
Предположим, что есть некоторый текст, recipepuppy.com, работающий на порте 80.
И мы не хотим жестко кодировать его в нашем приложении, мы хотим сделать ссылку на переменную. Мы можем экспортировать его в нашу оболочку и присвоить ей значение.
И мы можем сделать это немного более постоянным, если поместим его в наш bashrc.
Если мы посмотрим
tail
Мы увидим, что это находится в конце.
Итак, исполняем source
/.bashrc , чтобы объявить эту переменную среды.
Тогда мы можем использовать ее, к примеру, чтобы запустить в Chrome:
Добавляем также еще одну часть информации, это rb init. Он добавляет скрипты завершения команды.
Он также попадает в ваш путь, так что вы можете завершить частичные команды, которые вы запустили для Ruby.
После того, как он на месте, нужно просто сделать source, чтобы получить то, что мы только что вложили, в нашу оболочку.
Следующее, что мы вносим, это ruby-build, это дает нам возможность фактически установить ruby внутри rbenv.
Он будет установлен под home, ниже rbenv, в папке плагинов.
И, как и прежде, эта папка также должна быть добавлена в ваш путь.
Теперь, вот шаг, которого мы ждали. Здесь мы собираемся установить Ruby.
Вы заметите много компиляций, которые будут продолжаться. Можно ожидать, что это займет около 20-30 минут установки.
Итак, убедитесь, что вы ввели эту команду:
Затем можете пойти за чашкой кофе и бутербродом, пока идет установка.
Если будут какие-либо ошибки или остановки, скорее всего вам не хватает какого-то пакета. Если вы загуглите ошибку, вам будет легко найти чего вам не хватает.
Следующее, что мы сделаем, это установим версию Ruby по умолчанию, которая будет использоваться с этого момента. У нас уже есть Ruby, так что можем его использовать.
Проверяем:
ruby -v
Один из вариантов, который я предлагаю установить, заключается в том, чтобы сказать, чтобы gem’ы не генерировали локальную документацию. Это просто съедает дисковое пространство и время, когда они загружаются.
Затем устанавливаем менеджер gem’ов Rails. Это будет большим плюсом, когда мы начнем устанавливать gem’ы в наши приложения.
Теперь еще один интересный шаг. Теперь мы собираемся установить Rails.
Установка может занять несколько минут или около того.
После установки Rails, мы делаем rehash rbenv. Это советуют делать после установки любого gem’а, добавляющего команды.
Ruby и Rails готовы к использованию.
Затем мы собираемся установить одну из библиотек JavaScript, и здесь нам нужно дать Ubuntu некоторые уникальные инструкции.
Поэтому мы собираемся установить пару пакетов, которые вам нужны, чтобы все было подготовлено. Также устанавливаем местоположение для них.
И теперь финальные команды.
Затем мы собираемся установить PhantomJS. PhantomJS — это библиотека, которая позволяет нам проводить безгласное тестирование веб-приложений. Это значительно упростит модульное тестирование (юнит-тестирование), очень полезная вещь.
Мы начнем с того, что убедимся, что у нас есть bzip, потому что это будет частью наших шагов по установке.
Затем мы установим переменную среды, поэтому нам не нужно повторять себя, когда мы будем ссылаться на имя библиотеки.
Проверяем версию:
phantomjs -v
Как уже говорилось, разработчики обычно используют тот редактор кода который нравится, некоторые даже используют gedit как это делаю я. Но рассмотрим установку Sublime Text для логичного завершения этой статьи.
Источник