One place for hosting & domains

      Rails

      How To Install Ruby on Rails with rbenv on macOS


      Introduction

      Ruby on Rails is a popular application stack for developers looking to create sites and web apps. The Ruby programming language, combined with the Rails development framework, makes app development quick and efficient.

      One way to install Ruby and Rails is with the command-line tool rbenv. Using rbenv will provide you with a well-controlled and robust environment for developing your Ruby on Rails applications, allowing you to easily switch the version of Ruby for your entire team when needed.

      rbenv provides support for specifying application-specific versions of Ruby, lets you change the global Ruby for each user, and allows you to use an environment variable to override the Ruby version.

      In this tutorial, you will use rbenv to install and set up Ruby on Rails on your local macOS machine.

      Prerequisites

      To follow this tutorial, you will need:

      Step 1 — Installing rbenv

      In this step, you will install rbenv and make sure that it starts automatically at boot. To do this on macOS, this tutorial will use the package manager Homebrew.

      To download the rbenv package with Homebrew, run the following command:

      This will install rbenv and the ruby-build plugin. This plugin adds therbenv install command, which streamlines the installation process for new versions of Ruby.

      Next, you'll add the command eval "$(rbenv init -)" to your ~/.bash_profile file to make rbenv load automatically when you open up the Terminal. To do this, open your .bash_profile in your favorite text editor:

      Add the following line to the file:

      ~/.bash_profile

      eval "$(rbenv init -)"
      

      Save and quit the file.

      Next, apply the changes you made to your ~/.bash_profile file to your current shell session:

      To verify that rbenv is set up properly, use the type command, which will display more information about the rbenv command:

      Your terminal window will display the following:

      Output

      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 }

      At this point, you have both rbenv and ruby-build installed on your machine. This will allow you to install Ruby from the command line in the next step.

      Step 2 — Installing Ruby

      With the ruby-build plugin now installed, you can install any version of Ruby you may need through a single command. In this step, you will choose a version of Ruby, install it on your machine, and then verify the installation.

      First, use the -l flag to list all the available versions of Ruby:

      The output of that command will be a long list of versions that you can choose to install.

      For this tutorial, install Ruby 2.6.3:

      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:

      Your output will look something like this:

      Output

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

      To install and use a different version of Ruby, run the rbenv commands with a different version number, such as rbenv install 2.3.0 and rbenv global 2.3.0.

      You now have one version of Ruby installed and have set your default Ruby version. Next, you will set yourself up to work with Ruby packages and libraries, or gems, which will then allow you to install Rails.

      Step 3 — Working with Gems

      Gems are packages of Ruby libraries and programs that can be distributed throughout the Ruby ecosystem. You use the gem command to manage these gems. In this step, you will configure the gem command to prepare for the Rails installation.

      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:

      • echo "gem: --no-document" > ~/.gemrc

      With that done, use the gem command to install Bundler, a tool that manages gem dependencies for projects. This is needed for Rails to work correctly:

      You'll see output like this:

      Output

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

      You can use the gem env command to learn more about the environment and configuration of gems. To see the location of installed gems, use the home argument, like this:

      You'll see output similar to this:

      /Users/sammy/.rbenv/versions/2.6.3/lib/ruby/gems/2.6.0
      

      Now that you have set up and explored your gem workflow, you are free to install Rails.

      Step 4 — Installing Rails

      In this step, you will install Rails, verify the installation, and prepare it for use.

      To install the most recent version of Rails, use the gem install command:

      The gem command installs the gem you specify, as well as every dependency. Rails is a complex web development framework and has many dependencies, so the process will take some time to complete. Eventually you'll see a message stating that Rails is installed, along with its dependencies:

      Output

      ... Successfully installed rails-5.2.3 38 gems installed

      Note: If you would like to install a specific version of Rails, you can list its valid versions by doing a search, which will output a long list of options:

      • gem search '^rails$' --all

      You could then install a specific version, such as 4.2.7:

      • gem install rails -v 4.2.7

      rbenv works by creating a directory of shims, or libraries that intercept calls and change or redirect them. In this case, shims point Ruby commands 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, such as Rails, you should use rehash.

      To rehash the directory of shims, run the following command:

      Verify your installation of Rails by printing its version with this command:

      You will see the version of Rails that was installed:

      Output

      Rails 5.2.3

      With Rails successfully installed, you can begin testing your Ruby on Rails installation and start to develop web applications. In the next step, you will learn how to update and uninstall rbenv and Ruby.

      Step 5 — Updating and Uninstalling rbenv and Ruby

      When maintaining projects, it is useful to know how to update and uninstall when the need arises. In this step, you will upgrade rbenv, then uninstall Ruby and rbenv from your machine.

      You can upgrade rbenv and ruby-build using Homebrew by running the following command:

      • brew upgrade rbenv ruby-build

      If rbenv or ruby-build need to be updated, Homebrew will do it for you automatically. If your set up is already up to date, you will get output similar to the following:

      Output

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

      This will ensure that we are using the most up-to-date version of rbenv available.

      As you download additional versions of Ruby, you may accumulate more versions than you would like in your ~/.rbenv/versions directory. Using the ruby-build plugin's uninstall subcommand, you can remove these previous versions.

      For example, run the following to uninstall Ruby version 2.1.3:

      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.

      If you've decided you no longer want to use rbenv, you can remove it from your system.

      To do this, first open your ~/.bash_profile file in your editor:

      Find and remove the following line from the file to stop rbenv from starting when you open the Terminal:

      ~/.bash_profile

      ...
      eval "$(rbenv init -)"
      

      Once you have deleted this line, save the file and exit the editor.

      Run the following command to apply the changes to your shell:

      Next, remove rbenv and all installed Ruby versions with this command:

      Finally, remove the rbenv package itself with Homebrew:

      Check the rbenv version to make sure that it has been uninstalled:

      You will get the following output:

      Output

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

      This means that you have successfully removed rbenv from your machine.

      Conclusion

      In this tutorial you installed Ruby on Rails with rbenv on macOS. From here, you can learn more about coding in Ruby with our How To Code in Ruby series. You can also explore how to use Ruby on Rails with PostgreSQL rather than its default sqlite3 database, which provides more scalability, centralization, and stability for your applications.



      Source link

      How To Use PostgreSQL with Your Ruby on Rails Application on macOS


      Introduction

      When using the Ruby on Rails web framework, your application is set up by default to use SQLite as a database. SQLite is a lightweight, portable, and user-friendly relational database that performs especially well in low-memory environments, and will work well in many cases. However, for highly complex applications that need more reliable data integrity and programmatic extensibility, a PostgreSQL database will be a more robust and flexible choice. In order to configure your Ruby on Rails setup to use PostgreSQL, you will need to perform a few additional steps to get it up and running.

      In this tutorial, you will set up a Ruby on Rails development environment connected to a PostgreSQL database on a local macOS machine. You will install and configure PostgreSQL, and then test your setup by creating a Rails application that uses PostgreSQL as its database server.

      Prerequisites

      This tutorial requires the following:

      • One computer or virtual machine with macOS installed, with administrative access to that machine and an internet connection. This tutorial has been tested on macOS 10.14 Mojave.

      • A Ruby on Rails development environment installed on your macOS machine. To set this up, follow our guide on How To Install Ruby on Rails with rbenv on macOS. This tutorial will use version 2.6.3 of Ruby and 5.2.3 of Rails; for information on the latest versions, check out the official sites for Ruby and Rails.

      Step 1 — Installing PostgreSQL

      In order to configure Ruby on Rails to create your web application with PostgreSQL as a database, you will first install the database onto your machine. Although there are many ways to install PostgreSQL on macOS, this tutorial will use the package manager Homebrew.

      There are multiple Homebrew packages to install different versions of PostgreSQL. To install the latest version, run the following command:

      If you would like to download a specific version of PostgreSQL, replace postgresql in the previous command with your desired package. You can find the available packages at the Homebrew website.

      Next, include the PostgreSQL binary in your PATH variable in order to access the PostgreSQL command line tools, making sure to replace the 10 with the version number you are using:

      • echo 'export PATH="/usr/local/opt/postgresql@10/bin:$PATH"' >> ~/.bash_profile

      Then, apply the changes you made to your ~/.bash_profile file to your current shell session:

      To start the service and enable it to start at login, run the following:

      • brew services start postgresql@10

      Check to make sure the installation was successful:

      You will get the following output:

      Output

      postgres (PostgreSQL) 10.9

      Once PostgreSQL is installed, the next step is to create a role that your Rails application will use later to create your database.

      Step 2 — Creating a Database Role for Your Application

      In PostgreSQL, roles can be used to organize permissions and authorization. When starting PostgreSQL with Homebrew, you will automatically have a superuser role created with your macOS username. In order to keep these superuser privileges separate from the database instance you use for your Rails application, in this step you will create a new role with less access.

      To create a new role, run the following command, replacing appname with whatever name you'd like to give the role:

      In this command, you used createuser to create a role named appname. The -d flag gave the role the permission to create new databases.

      You also specified the -P flag, which means you will be prompted to enter a password for your new role. Enter your desired password, making sure to record it so that you can use it in a configuration file in a future step.

      If you did not use the -P flag and want to set a password for the role after you create it, enter the PostgreSQL console with the following command:

      You will receive the following output, along with the prompt for the PostgreSQL console:

      Output

      psql (10.9) Type "help" for help. postgres=#

      The PostgreSQL console is indicated by the postgres=# prompt. At the PostgreSQL prompt, enter this command to set the password for the new database role, replacing the highlighted name with the one you created:

      PostgreSQL will prompt you for a password. Enter your desired password at the prompt, then confirm it.

      Now, exit the PostgreSQL console by entering this command:

      Your usual prompt will now reappear.

      In this step, you created a new PostgreSQL role without superuser privileges for your application. Now you are ready to create a new Rails app that uses this role to create a database.

      Step 3 — Creating a New Rails Application

      With your role configured for PostgreSQL, you can now create a new Rails application that is set up to use PostgreSQL as a database.

      First, navigate to your home directory:

      Create a new Rails application in this directory, replacing appname with whatever you would like to call your app:

      • rails new appname -d=postgresql

      The -d=postgresql option sets PostgreSQL as the database.

      Once you've run this command, a new folder named appname will appear in your home directory, containing all the elements of a basic Rails application.

      Next, move into the application's directory:

      Now that you have created a new Rails application and have moved into the root directory for your project, you can configure and create your PostgreSQL database from within your Rails app.

      Step 4 — Configuring and Creating Your Database

      When creating the development and test databases for your application, Rails will use the PostgreSQL role that you created in Step 2. To make sure that Rails creates these databases, you will alter the database configuration file of your project. You will then create your databases.

      One of the configuration changes to make in your Rails application is to add the password for the PostgreSQL role you created in the last step. To keep sensitive information like passwords safe, it is a good idea to store this in an environment variable rather than to write it directly in your configuration file.

      To store your password in an environment variable at login, run the following command, replacing APPNAME with the name of your app and PostgreSQL_Role_Password with the password you created in the last step:

      • echo 'export APPNAME_DATABASE_PASSWORD="PostgreSQL_Role_Password"' >> ~/.bash_profile

      This command writes the export command to your ~/.bash_profile file so that the environment variable will be set at login.

      To export the variable for your current session, use the source command:

      Now that you have stored your password in your environment, it's time to alter the configuration file.

      Open your application's database configuration file in your preferred text editor. This tutorial will use nano:

      Under the default section, find the line that says pool: <%= ENV.fetch("RAILS_MAX_THREADS") { 5 } %> and add the following highlighted lines, filling in your credentials and the environment variable you created. It should look something like this:

      config/database.yml

      ...
      default: &default
        adapter: postgresql
        encoding: unicode
        # For details on connection pooling, see Rails configuration guide
        # http://guides.rubyonrails.org/configuring.html#database-pooling
        pool: <%= ENV.fetch("RAILS_MAX_THREADS") { 5 } %>
        username: appname
        password: <%= ENV['APPNAME_DATABASE_PASSWORD'] %>
      
      development:
        <<: *default
        database: appname_development
      ...
      

      This will make the Rails application run the database with the correct role and password. Save and exit by pressing CTRL+X, Y, then ENTER.

      For more information on configuring databases in Rails, see the Rails documentation.

      Now that you have made changes to config/database.yml, create your application's databases by using the rails command:

      Once Rails creates the database, you will receive the following output:

      Output

      Created database 'appname_development' Created database 'appname_test'

      As the output suggests, this command created a development and test database in your PostgreSQL server.

      You now have a PostgreSQL database connected to your Rails app. To ensure that your application is working, the next step is to test your configuration.

      Step 5 — Testing Your Configuration

      To test that your application is able to use the PostgreSQL database, try to run your web application so that it will show up in a browser.

      First, you'll use the built-in web server for Rails, Puma, to serve your application. This web server comes with Rails automatically and requires no additional setup. To serve your application, run the following command:

      • rails server --binding=127.0.0.1

      --binding binds your application to a specified IP. By default, this flag will bind Rails to 0.0.0.0, but since this means that Rails will listen to all interfaces, it is more secure to use 127.0.0.1 to specify the localhost. By default, the application listens on port 3000.

      Once your Rails app is running, your command prompt will disappear, replaced by this output:

      Output

      => Booting Puma => Rails 5.2.3 application starting in development => Run `rails server -h` for more startup options Puma starting in single mode... * Version 3.12.1 (ruby 2.6.3-p62), codename: Llamas in Pajamas * Min threads: 5, max threads: 5 * Environment: development * Listening on tcp://127.0.0.1:3000 Use Ctrl-C to stop

      To test if your application is running, open up a new terminal window on your server and use the curl command to send a request to 127.0.0.1:3000:

      • curl http://127.0.0.1:3000

      You will receive a lot of output in HTML, ending in something like:

      Output

      ... <strong>Rails version:</strong> 5.2.3<br /> <strong>Ruby version:</strong> 2.6.3 (x86_64-darwin18) </p> </section> </div> </body> </html>

      You can also access your Rails application in a local web browser by visiting:

      http://127.0.0.1:3000
      

      At this URL, you will find a Ruby on Rails welcome page:

      Ruby on Rails Welcome Page

      This means that your application is properly configured and connected to the PostgreSQL database.

      Conclusion

      In this tutorial, you created a Ruby on Rails web application that was configured to use PostgreSQL as a database on a local macOS machine. If you would like to learn more about the Ruby programming language, check out our How To Code in Ruby series.

      For more information on choosing a database for your application, check out our tutorial on the differences between and use cases of SQLite, PostgreSQL, and MySQL. If you want to read more about how to use databases, see our An Introduction to Queries in PostgreSQL article, or explore DigitalOcean's Managed Databases product.



      Source link

      How To Use PostgreSQL with Your Ruby on Rails Application on Ubuntu 18.04


      Introduction

      When using the Ruby on Rails web framework, your application is set up by default to use SQLite as a database. SQLite is a lightweight, portable, and user-friendly relational database that performs especially well in low-memory environments, and will work well in many cases. However, for highly complex applications that need more reliable data integrity and programmatic extensibility, a PostgreSQL database will be a more robust and flexible choice. In order to configure your Ruby on Rails setup to use PostgreSQL, you will need to perform a few additional steps to get it up and running.

      In this tutorial, you will set up a Ruby on Rails development environment connected to a PostgreSQL database on an Ubuntu 18.04 server. You will install and configure PostgreSQL, and then test your setup by creating a Rails application that uses PostgreSQL as its database server.

      Prerequisites

      This tutorial requires the following:

      Step 1 – Installing PostgreSQL

      In order to configure Ruby on Rails to create your web application with PostgreSQL as a database, you will first install the database onto your server.

      Using sudo privileges, update your APT package index to make sure that your repositories are up to date:

      Next, install PostgreSQL and its development libraries:

      • sudo apt install postgresql postgresql-contrib libpq-dev

      In the previous command, the postgresql package holds the main PostgreSQL program, while postgresql-contrib adds several PostgreSQL features that extend its capabilities. libpq-dev is a PostgreSQL library that allows clients to send queries and receive responses from the back-end server, which will allow your application to communicate with its database.

      Once PostgreSQL and its dependencies are installed, the next step is to create a role that your Rails application will use later to create your database.

      Step 2 – Creating a New Database Role

      In PostgreSQL, roles can be used in the same way as users in Linux to organize permissions and authorization. This step will show you how to create a new super user role for your Linux username that will allow you to operate within the PostgreSQL system to create and configure databases.

      To create a PostgreSQL super user role, use the following command, substituting the highlighted word with your Ubuntu 18.04 username:

      • sudo -u postgres createuser -s sammy -P

      Since you specified the -P flag, you will be prompted to enter a password for your new role. Enter your desired password, making sure to record it so that you can use it in a configuration file in a future step.

      In this command, you used createuser to create a role named sammy. The -s gave this user super user privileges, and sudo -u allowed you to run the command from the postgres account that is automatically created upon installing PostgreSQL.

      Note: Since the authentication mode for PostgreSQL on Ubuntu 18.04 starts out as ident, by default an Ubuntu user can only operate in PostgreSQL with a role of the same name. For more information, check out the PostgreSQL official documentation on authentication.

      If you did not use the -P flag and want to set a password for the role after you create it, enter the PostgreSQL console with the following command:

      You will receive the following output, along with the prompt for the PostgreSQL console:

      Output

      psql (10.9 (Ubuntu 10.9-0ubuntu0.18.04.1)) Type "help" for help. postgres=#

      The PostgreSQL console is indicated by the postgres=# prompt. At the PostgreSQL prompt, enter this command to set the password for the new database role, replacing the highlighted name with the one you created:

      PostgreSQL will prompt you for a password. Enter your desired password at the prompt, then confirm it.

      Now, exit the PostgreSQL console by entering this command:

      Your usual prompt will now reappear.

      In this step, you created a new PostgreSQL role with super user privileges. Now you are ready to create a new Rails app that uses this role to create a database.

      Step 3 – Creating a New Rails Application

      With a role configured for PostgreSQL, you can now create a new Rails application that is set up to use PostgreSQL as a database.

      First, navigate to your home directory:

      Create a new Rails application in this directory, replacing appname with whatever you would like to call your app:

      • rails new appname -d=postgresql

      The -d=postgresql option sets PostgreSQL as the database.

      Once you've run this command, a new folder named appname will appear in your home directory, containing all the elements of a basic Rails application.

      Next, move into the application's directory:

      Now that you have created a new Rails application and have moved into the root directory for your project, you can configure and create your PostgreSQL database from within your Rails app.

      Step 4 – Configuring and Creating Your Database

      When creating the development and test databases for your application, Rails will use the PostgreSQL role that you created for your Ubuntu username. To make sure that Rails creates these databases, you will alter the database configuration file of your project. You will then create your databases.

      One of the configuration changes to make in your Rails application is to add the password for the PostgreSQL role you created in the last step. To keep sensitive information like passwords safe, it is a good idea to store this in an environment variable rather than to write it directly in your configuration file.

      To store your password in an environment variable at login, run the following command, replacing APPNAME with the name of your app and PostgreSQL_Role_Password with the password you created in the last step:

      • echo 'export APPNAME_DATABASE_PASSWORD="PostgreSQL_Role_Password"' >> ~/.bashrc

      This command writes the export command to your ~/.bashrc file so that the environment variable will be set at login.

      To export the variable for your current session, use the source command:

      Now that you have stored your password in your environment, it's time to alter the configuration file.

      Open your application's database configuration file in your preferred text editor. This tutorial will use nano:

      Under the default section, find the line that says pool: <%= ENV.fetch("RAILS_MAX_THREADS") { 5 } %> and add the following highlighted lines, filling in your credentials and the environment variable you created. It should look something like this:

      config/database.yml

      ...
      default: &default
        adapter: postgresql
        encoding: unicode
        # For details on connection pooling, see Rails configuration guide
        # http://guides.rubyonrails.org/configuring.html#database-pooling
        pool: <%= ENV.fetch("RAILS_MAX_THREADS") { 5 } %>
        username: sammy
        password: <%= ENV['APPNAME_DATABASE_PASSWORD'] %>
      
      development:
        <<: *default
        database: appname_development
      ...
      

      This will make the Rails application run the database with the correct role and password. Save and exit by pressing CTRL + x, Y, then ENTER.

      For more information on configuring databases in Rails, see the Rails documentation.

      Now that you have made changes to config/database.yml, create your application's databases by using the rails command:

      Once Rails creates the database, you will receive the following output:

      Output

      Created database 'appname_development' Created database 'appname_test'

      As the output suggests, this command created a development and test database in your PostgreSQL server.

      You now have a PostgreSQL database connected to your Rails app. To ensure that your application is working, the next step is to test your configuration.

      Step 5 – Testing Your Configuration

      To test that your application is able to use the PostgreSQL database, try to run your web application so that it will show up in a browser.

      Using the rails server command, run your web application on the built-in webserver in your Rails app, Puma:

      • rails server --binding=127.0.0.1

      --binding binds your application to a specified IP. By default, this flag will bind Rails to 0.0.0.0, but since this means that Rails will listen to all interfaces, it is more secure to use 127.0.0.1 to specify the localhost. By default, the application listens on port 3000.

      Once your Rails app is running, your command prompt will disappear, replaced by this output:

      Output

      => Booting Puma => Rails 5.2.3 application starting in development => Run `rails server -h` for more startup options Puma starting in single mode... * Version 3.12.1 (ruby 2.6.3-p62), codename: Llamas in Pajamas * Min threads: 5, max threads: 5 * Environment: development * Listening on tcp://127.0.0.1:3000 Use Ctrl-C to stop

      To test if your application is running, open up a new terminal window on your server and use the curl command to send a request to 127.0.0.1:3000:

      • curl http://127.0.0.1:3000

      You will receive a lot of output in HTML, ending in something like:

      Output

      ... <strong>Rails version:</strong> 5.2.3<br /> <strong>Ruby version:</strong> 2.6.3 (x86_64-linux) </p> </section> </div> </body> </html>

      If your Rails application is on a remote server and you want to access it through a web browser, an easy way is to bind it to the public IP address of your server. First, open port 3000 in your firewall:

      Next, look up the public IP address of your server. You can do this by running the following curl command:

      • curl http://icanhazip.com

      This will return your public IP address. Use it with the rails server command, substituting server_public_IP with your server's public IP:

      • rails server --binding=server_public_IP

      Now you will be able to access your Rails application in a local web browser via the server's public IP address on port 3000 by visiting:

      http://server_public_IP:3000
      

      At this URL, you will find a Ruby on Rails welcome page:

      Ruby on Rails Welcome Page

      This means that your application is properly configured and connected to the PostgreSQL database.

      After testing the configuration, if you would like to close port 3000, use the following command.

      • sudo ufw delete allow 3000

      Conclusion

      In this tutorial, you created a Ruby on Rails web application that was configured to use PostgreSQL as a database on an Ubuntu 18.04 server. If you would like to learn more about the Ruby programming language, check out our How To Code in Ruby series.

      For more information on choosing a database for your application, check out our tutorial on the differences between and use cases of SQLite, PostgreSQL, and MySQL. If you want to read more about how to use databases, see our An Introduction to Queries in PostgreSQL article, or explore DigitalOcean's Managed Databases product.



      Source link