#Setting up your computer for Ruby on Rails on Mac
#####tl;dr
$ curl -sSL https://get.rvm.io | bash -s stable && source ~/.rvm/scripts/rvm # Get latest Ruby using RVM
$ gem install rails # Get Rails
$ ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)" # Get Homebrew
$ brew install postgresql # Get Postgresql
$ brew install git # Get Git
Ruby on Rails is a popular framework for making web applications, here's how to get set up on Mac.
This tutorial relies on using a command-line interface like Terminal or PowerShell. If you're brand new to coding, or haven't used a command-line interface before, familiarise yourself with the basics through this tutorial before continuing.
###Ruby
Manage your Ruby installations with RVM – Ruby enVironment Manager. At http://rvm.io/ you'll find detailed documentation on the features available with this software. It allows you to install multiple versions of Ruby and switch easily between them, which you'll find invaluable when working on multiple projects each relying on different versions of Ruby.
Install it by opening up your preferred command-line interface and typing this command-line:
$ curl -sSL https://get.rvm.io | bash -s stable
Note that where code is specefied in this article the dollar sign
$
represents a prompt. A prompt is a sequence of one or more characters in a command-line interface that indicate that the computer is ready to accept typed input. You do not need to type the dollar sign$
into your command-line interface, only the commands that follow it.
Close and reopen Terminal and use RVM to install the latest Ruby:
$ ruby -v
ruby 2.0.0p451 (2014-02-24 revision 45167) [universal.x86_64-darwin13]
$ rvm install 2.1.2
$ ruby -v
ruby 2.1.2p95 (2014-05-08 revision 45877) [x86_64-darwin13.0]
###Gems
Ruby developers often package their code according to the same conventions. The package manager responsible for downloading, installing and using Ruby packages is called RubyGems. The software packages themselves are known as Gems. More information on Ruby's package manager is available at http://guides.rubygems.org/.
We can use the RubyGems software at the command-line with the gem
command available since we used RVM to install a Ruby version.
Let's use RubyGems to install rails:
$ gem install rails
###Rails
Now that we've installed Ruby on Rails we should have access to the rails
command, which allows us to create a new Rails application with a default directory structure and configuration at the path you specify.
$ rails new path/to/my/new_project
$ cd path/to/my/new_project
$ rails server
=> Booting WEBrick
=> Rails 4.1.6 application starting in development on http://0.0.0.0:3000
=> Run `rails server -h` for more startup options
=> Notice: server is listening on all interfaces (0.0.0.0). Consider using 127.0.0.1 (--binding option)
=> Ctrl-C to shutdown server
[2014-10-28 16:31:07] INFO WEBrick 1.3.1
[2014-10-28 16:31:07] INFO ruby 2.1.2 (2014-05-08) [x86_64-darwin13.0]
[2014-10-28 16:31:07] INFO WEBrick::HTTPServer#start: pid=59365 port=3000
Point your browser at http://0.0.0.0:3000/ to see instructions on how to use Rails.
The links picture on the right of the image are very useful resources for getting started with Ruby on Rails. The Rails Guides in particular have a very useful getting started guide for beginners.
From here you can dive right in and learn about how to code websites with Rails. The rest of this article covers putting a Rails app online using Heroku as a hosting platform.
Homebrew is a package manager for OSX. Use it to manage installations and easily update software dependencies. Go to http://brew.sh for more information.
It's an incredibly useful tool for getting and managing all sorts of software. We're going to use it in the next step to install some database management and version control software.
$ ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)"
Close and reopen Terminal to use the brew
command.
###Git
Git is a powerful and popular tool for keeping track of changes to code. Tracking changes and keeping the entire history of a project is an indespensible part of working with code and is called version control.
Download Git with Homebrew.
$ brew install git
There are clients available but the best way to use Git is via the command-line. There are four basic steps:
- Initialise the project as a repository of code.
- Add changes to the staging area.
- Commit the changes to Git.
- Push the code to a remote repository.
$ init
$ add
$ commit
$ push
The first step is only required once per project and steps 2 to 4 are to be repeated everytime the code-base is altered.
- Add
- Commit
- Push
#####Initialising a repo
$ git init
This adds a .git
folder which contains the version history of the entire directory tree. We don't use this folder except indirectly via git
commands.
Once a project is initialised as a git repository (repo for short) we have access to a suite of Git commands for interacting with our version history. For this tutorial let's cover steps 2 to 4. For more info on Git see future posts by me or check out http://scm-git.com/.
#####Add changes to the staging area
$ git add .
This command adds any changes to the staging area. The changes have to have been made to files in the initialised repo, that means they are in the current directory (folder) or any files in any descendent folder.
.
├── Gemfile
├── Gemfile.lock
├── README.rdoc
├── Rakefile
├── app
│ ├── assets
│ │ ├── images
│ │ ├── javascripts
│ │ │ ├── application.js
│ │ │ └── posts.js.coffee
│ │ └── stylesheets
│ │ ├── application.css
│ │ ├── posts.css.scss
│ │ └── scaffolds.css.scss
│ ├── controllers
│ │ ├── application_controller.rb
│ │ ├── concerns
│ │ └── posts_controller.rb
│ ├── helpers
│ │ ├── application_helper.rb
│ │ └── posts_helper.rb
│ ├── mailers
│ ├── models
│ │ ├── concerns
│ │ └── post.rb
│ └── views
│ ├── layouts
│ │ └── application.html.erb
│ └── posts
│ ├── _form.html.erb
│ ├── edit.html.erb
│ ├── index.html.erb
│ ├── index.json.jbuilder
│ ├── new.html.erb
│ ├── show.html.erb
│ └── show.json.jbuilder
$ git commit -m 'initial commit'
This saves the changes to the git repository.
In order to send the code to a remote repository, we have to register with a web service that allows us to create repos on their servers to push to.
GitHub is a popular choice and was built using Ruby on Rails.
Just as we had to initialize our local project directory as a git
repo, the same is true for the remote project folder. On GitHub we do that like this.
GitHub will remind you of the steps needed to connect your local repo with the remote you just created.
$ git remote add origin [email protected]:tmcdb/my_first_rails_app.git
$ git push -u origin master
By adding, commiting and pushing changes made to your code hereafter, you can safely and confidently plough on and experimeng without fear.
To make the most of collaborating on projects you'll need to learn a little about git pull
, git merge
, and issues and pull requests on GitHub.
It's really useful to use commands that give you information about your git repo.
$ git status
This outputs information about changes that have been made to your files, whether they've been added to the staging area or whether they've been commited and more.
$ git remote -v
Git remote on it's own with the -v
(for verbose) flag outputs the names and destinations of remote repos for the project.
###PostgreSQL
PostgreSQL is Object-Relational Database Management System (ORDBMS) software. Installing PostgreSQL enables you to create, connect with, store, retrieve and delete data in an object-relational database.
#####Why do we need it?
By default Rails apps are configured to use SQLite, a serverless, zero-configuration database engine. It's ideal for getting setup quickly in your development environment (running the app on your machine while you're building it) because it requires no separate server process to install, setup, configure, initialize, manage, and troubleshoot. It is not recommended to use a serverless database engine for production (hosting the app on the web with real data).
Rails apps, and other back-end apps, can be run under one of three environments: development, test and production. The difference between them depends on their configuration.
PostgreSQL is a good fit for a production database and it's Heroku's choice for Rails app – more on Heroku later.
Hosting your code on Heroku requires the pg
Gem, which is a Ruby interface to PostgreSQL. Installing and using the pg
Gem requires an installation of PostgreSQL.
We can install PostgreSQL using Homebrew.
First make sure Homebrew is up to date.
$ brew update
Then install PostgreSQL.
$ brew install postgresql
While Homebrew downloads and installs PostgreSQL you'll see a lot of output in the window into which you typed the command. This is normal. You'll know it's finished when your prompt reapears.
Once complete you'll need to create a new PostgreSQL database cluster. This is a configuration step, after which you'll be able to use PostgreSQL, which we'll be doing via the pg
Gem in a Rails app to create databases.
The initdb
command is for creating a cluster.
$ initdb /usr/local/var/postgres -E utf8
This initialise a database cluster at the path specefied and sets it up to use utf-8 character encoding.
###The pg
Gem
The pg
Gem is a Ruby interface to PostgreSQL. To configure a Rails app for hosting on Heroku the pg
must be specefied in the Gemfile and bundled into the app.
There is already a database Gem specefied in the Gemfile
called sqlite3
and you can't specify more than one for one environment. There are two options available, either remove the sqlite3
Gem completely and use PostgreSQL in development or specify sqlite3
in development and test environments and pg
for the production environment.
The latter option is the easier of the two. The first option is a better solution but it requires more setup.
To set up for different databases per environment the following syntax is available in the Gemfile. See Bundler's docs for more details.
# Gemfile
group :development, :test do
gem 'sqlite'
end
group :production do
gem 'pg'
end
$ bundle install
To set up for parity between environments we must run a postgres
instance. A postgres
instance is the PostgreSQL database server process. There are PostgreSQL commands for running a postgres
database server and the pg_ctl
utility wraps them in a simpler syntax. Once a postgres
server is running on your machine you can configure your app to connect with it when you run it locally with rails s
. Here's how:
# Gemfile
gem `pg`
Use the command pg_ctl
to run a database server in the background.
$ pg_ctl start -D /usr/local/var/postgres -l /usr/local/var/postgres/server.log
The first argument start
to the command above launches the server. The -D
flag in the command above tells PostgreSQL the file system location of the database files. The -l
flag tells PostgreSQL in what file to append the server log output.
Before we run the Rails app we need to configure it to recognise the correct database adapter.
# 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: 5
development:
<<: *default
database: my_app_name_development
# Warning: The database defined as "test" will be erased and
# re-generated from your development database when you run "rake".
# Do not set this db to the same as development or production.
test:
<<: *default
database: my_app_name_test
production:
<<: *default
database: my_app_name_production
username: my_app_name
password: <%= ENV['MY_APP_NAME_DATABASE_PASSWORD'] %>
To use PostgreSQL in development you always have to make sure you're running the postgres
server instance as demonstrated earlier with the pg_ctl
command. I like to make use of shell aliases to contract verbose and cumbersome commands into more friendly concise shortcuts.
# ~/.bashrc
alias pgstart='pg_ctl -D /usr/local/var/postgres -l /usr/local/var/postgres/server.log start'
alias pgstop='pg_ctl -D /usr/local/var/postgres stop -s -m fast'
Saving the two lines above to shell configuration file will make pgstart
and pgstop
available as commands. Make sure to restart the shell in order to load the aliased commands into the shell environment.
Learn more about shell configuration in this post.
Whenever we want to develop with Postgres in development we'll have to run the database server instance with the pgstart
alias before trying to run the app.
###Heroku
Heroku is a cloud application hosting platform for building and deploying web apps. They provide a service which abstracts many of the steps from server configuration and maintainance that are normally the bugbear of web developers. The Heroku toolbelt consists of a suite of concise commands for interfacing with your app on the server.
If you've followed one of the steps above to configure an app to use the PostgreSQL database adapter in production you're ready to download and use the Heroku toolbelt to deploy the app live.
Go to http://toolbelt.heroku.com/ and click the download link. Open up a terminal window with your preferred CLI and type heroku
to see the commands available.
Usage: heroku COMMAND [--app APP] [command-specific-options]
Primary help topics, type "heroku help TOPIC" for more details:
addons # manage addon resources
apps # manage apps (create, destroy)
auth # authentication (login, logout)
config # manage app config vars
domains # manage custom domains
logs # display logs for an app
ps # manage dynos (dynos, workers)
releases # manage app releases
run # run one-off commands (console, rake)
sharing # manage collaborators on an app
Additional topics:
certs # manage ssl endpoints for an app
drains # display syslog drains for an app
features # manage optional features
fork # clone an existing app
git # manage git for apps
help # list commands and display help
keys # manage authentication keys
labs # manage optional features
maintenance # manage maintenance mode for an app
members # manage membership in organization accounts
orgs # manage organization accounts
pg # manage heroku-postgresql databases
pgbackups # manage backups of heroku postgresql databases
plugins # manage plugins to the heroku gem
regions # list available regions
stack # manage the stack for an app
status # check status of heroku platform
twofactor #
update # update the heroku client
version # display version
We'll use the create command to make a remote Git repo on Heroku's servers.
$ heroku create
Take a look at your domain and confirm that it's available on the web:
$ heroku open
Use git remote
to see the remote repo called heroku
.
To deploy the code we use Git.
$ git push heroku master
Now if you open your browser at the URL you'll see 500 error.
$ heroku open
Rake the database remotely to set up the database on the server:
$ heroku run rake db:migrate
$ heroku open
The end.
I hope that was helpful. Send me feedback at [email protected].