Technical Blog


How to Set Up a Basic Ruby Environment With a Console

Hello there. Below is a quick guide on setting up a basic environment in Ruby with a console for you to play with your objects:

In your project directory, create a config directory. WIthin that directory, create an environment.rb file.

                Directory Structure for Sample Project:
                
                Newsletter-cli-app
                  lib
                    newsletter.rb
                    article.rb
                  config
                    environment.rb
                
                
In environment.rb, we will automatically load gem dependencies with Bundler.require and also allow access to our object class files within lib.
              
              # /config/environment.rb
              
              require 'bundler'
              
              Bundler.require
              
              require_all './lib
              
              
Now we need to make sure we have a few gems. Create a Gemfile within the project directory and add the gems we'll need:
              
              # /Gemfile
              
              source 'https://rubygems.org'
              
              gem 'rake'
              gem 'pry'
              gem 'require_all'
              
              
Next, let's create a Rakefile within our project directory so that we will be able to create a Rake console task that will start the Pry console.
              
              # /Rakefile
              
              require_relative './config.environment'
              
              task :console do
                Pry.start
              end
              
              
Your directory structure should be looking something like this:
              Newsletter-cli-app
                lib
                  newsletter.rb
                  article.rb
                config
                  environment.rb
                Gemfile
                Rakefile
              
To finsish up, run bundle in terminal within the project directory and your depencies will install. Woohoo! You're done. Run rake console to open up the sandbox you've just created and start interacting with your objects.