Skip to content

Instantly share code, notes, and snippets.

@wazery
Created January 26, 2014 21:37
Show Gist options
  • Save wazery/8639801 to your computer and use it in GitHub Desktop.
Save wazery/8639801 to your computer and use it in GitHub Desktop.
Getting started with Ruby on Rails
Getting started with Ruby on Rails
=====================
#Contents
- What is Ruby
- RubyGems
- Ruby Version Manager (RVM)
- Ruby Installation
- Windows
- Mac OS X
- Linux
- What is irb
- Major Ruby features
- Objects
- Symbols
- Conditionals
- Loops
- Classes and Modules
- Embedded Ruby
- What is Rails
- Rails architecture
In this tutorial I will introduce you to the basics of the Ruby language and the Rails framework. In the next tutorial I will create a simple web application using RoR.
----------
What is Ruby
============
Ruby is a programming language that has an elegant syntax. Ruby came out in February 24, 1993 by a Japanese computer programmer called **"Yukihiro Matsumoto"** a.k.a. **"Matz"**. Ruby is a language of careful balance. Its creator, “Matz”, blended parts of his favorite languages (Perl, Smalltalk, Eiffel, Ada, and Lisp) to form a new language that balanced their features with beautiful, easy, natural syntax. One of the goals is to create a language which is more object oriented than Python and more powerful than Perl. All of this led to Ruby’s core principle: Everything is an object. Its fans call it a beautiful, artful language. And yet, they say it’s handy and practical.
Ruby Gems
=========
Ruby has a very handy package manager called RubyGems, it provide a way to create Ruby packages easily. This packages are called Gems, each package contains package information and the files to be installed. There is a popular community that hosts this packages called [rubygems.org][1]. RubyGems is used with the `gem` command, in which you can download, install, and build gems. Here are some few examples of its usage:
> gem install paperclip --version ">= 2.7.0"
Or un-installing it by:
> gem uninstall paperclip
Or listing gems
> gem list
We will explain how to install it later in this tutorial.
Ruby Version Manager (RVM)
========================
**RVM** is a command-line tool which allows you to easily install, manage, and work with multiple ruby versions on the same machine. You may have multiple projects each with a different Ruby version and you need to work with them at the same time, it will be hard and tedious job to change your installed version manually, but with the RVM you can manage this very easily, 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. RVM is popular, well-supported, and full-featured. If you are an experienced Unix administrator, you can consider alternatives such as [Chruby][2], Sam Stephenson’s [rbenv][3].
Ruby On Rails Installation
==================
Lets see how we can install all the required libraries for Ruby on Rails. To begin creating Ruby on Rails applications we need the following installed:
- Ruby - the language
- Ruby Gems - the plugin/package manager for Ruby
- Rails Framework
- Web Server
- Database System
After installing Ruby you will get the WEBrick Web Server installed, you can also install other Web Servers of your choice like Apache or Nginx.
Rails works with many database systems, including MySQL,PostgreSQL, SQLite, Oracle, DB2 and SQL Server. In this tutorial we are going to use SQLite. Please refer to a corresponding Database System Setup manual to setup your database.
Lets look at the installation instructions for Rails on Windows, Mac OS X, and Linux.
#Installation on Windows
- **STEP 1:** First, let's check to see if you already have Ruby installed. Bring up a command prompt and type `ruby -v`. If Ruby responds, and if it shows a version number at or above 1.8.2 then type `gem --version`. If you don't get an error, skip to *`step 3`*. Otherwise, we'll install a fresh Ruby.
- **STEP 2:** If Ruby is not installed, then download an installation package from [rubyinstaller][4]. Follow the download link, and run the resulting installer. This is an exe like `ruby186-25.exe` and will be installed in a single click. You may as well install everything . It's a very small package, and you'll get RubyGems as well along with this package. Please check Release Notes for more detail.
- **STEP 3:** With RubyGems loaded, you can install all of Rails and its dependencies through the command line, just make sure you are connected to the Internet and now is the time for coffee, just make a cup and leave the following line do the installation for you.
> C:\> gem install rails --include-dependencies
And now you will have Rails installed with all its dependencies.
#Installation on Mac OS X
- **STEP 1:** First, let's check to see if you already have Ruby installed. Bring up a command prompt and type `ruby -v`. If Ruby responds, and if it shows a version number at or above 1.8.2 then type `gem --version`. If you don't get an error, skip to *`step 3`*. Otherwise, we'll install a fresh Ruby.
- **STEP 2:** Next you have to install RubyGems. Go to [rubygems.org][5] and follow the download link. OS X will typically unpack the archive file for you, so all you have to do is navigate to the downloaded directory and (in the Terminal application) type.
>$ tar xzf rubygems-2.1.11.tgz
$ cd rubygems-2.1.11
rubygems-2.1.11$ sudo ruby setup.rb
- **STEP 3:** Now use RubyGems to install Rails, you can install all of Rails and its dependencies through the terminal, just make sure you are connected to the Internet and now is the time for coffee, just make a cup and leave the following line do the installation for you.
> $ sudo gem install rails --include-dependencies
After that you will get Rails installed with all its dependencies.
#Installation on Linux
- **STEP 1:** First, let's check to see if you already have Ruby installed. Bring up a command prompt and type `ruby -v`. If Ruby responds, and if it shows a version number at or above 1.8.2 then type `gem --version`. If you don't get an error, skip to *`step 3`*. Otherwise, we'll install a fresh Ruby.
- **STEP 2:** Install Ruby with RVM, before we do anything else, we should run a quick update to make sure that all of the packages are up to date.
> sudo apt-get update
- **STEP 3:** If you do not have curl on your system, you can start by installing it:
> sudo apt-get install curl
- **STEP 4:** To install RVM, open terminal and type in this command:
> curl -L https://get.rvm.io | bash -s stable
- **STEP 5:** After it is done installing, load RVM. You may first need to exit out of your shell session and start up a new one.
> source ~/.rvm/scripts/rvm
- **STEP 6:** In order to work, RVM has some of its own dependencies that need to be installed. To automatically install them:
> rvm requirements
- **STEP 7:** Now we can install Ruby with RVM:
> rvm install ruby
- **STEP 8:** Now After Ruby is installed we need to specify which version of Ruby to be used, in this case we will use the default version, with the following command:
> rvm use ruby --default
- **STEP 9:** Now we need to install RubyGems, so simply we will use RVM to install it:
> rvm rubygems current
- **STEP 10:** Now we are ready to install Rails, so lets do it with RVM:
> gem install rails
**NOTE:** You may need to have system modification privileges, so use `Sudo` if it is required.
Now we installed Ruby and Rails with the RVM, and we are ready!
What is irb
============
**irb** is an abbreviation for Interactive Ruby Shell. This abbreviation comes from the Ruby filename extension which is ".rb". It is a command prompt (shell) program for experimenting Ruby, you can launch it after installing Ruby from the command line. You can execute Ruby syntax line by line in it. Here what it looks like:
irb(main):001:0> x = 2
=> 2
irb(main):002:0> x * 2
=> 4
irb(main):003:0> x + 2
=> 4
irb(main):004:0> def sum (x,y)
irb(main):005:1> x + y
irb(main):006:1> end
irb(main):007:0> sum(2,3)
=> 5
The above is what it looks in my command line. As you can see you can execute some simple lines of code, and also you can execute larger snippets line by line. You can see this`:001:0>`which is the line number along with indentation level, see in line 5 the indentation level is 1 `:005:1>` because the line is inside the def declaration which we will explain later.
Ruby Scripts
============
Like all the interpreted scripting languages Ruby offers to create script files with the extension ".rb". Lets create our first script. Open your favourite text editor and just type `puts "Hello Ruby"`, save the file with any name you want (mine is helloRuby.rb) and make sure to add the ".rb" extension.
Open the command line and type `ruby helloRuby.rb`. You will get "Hello Ruby" printed.
Classes and Modules
===============
To implement object-oriented programming by using Ruby, you need to first learn how to create objects and classes in Ruby.
A class in Ruby always starts with the keyword class followed by the name of the class. The name should always be in initial capitals. The class Building can be displayed as:
class Building
code..
end
You terminate a class by using the keyword `end`. All the data members in the class are between the class definition and the `end` keyword.
Objects
========
Classes can be instantiated to create objects in Ruby everything is an object, literals are objects, `True` and `False` also are objects. You can call methods on Literals:
10.next
=> 11
Objects are very important in Ruby, you use them in every aspect, if you have an employee object and you want to know if he works for a specific employer you simply asks the employee object itself, rather than asking in abstract. Hence any data manipulation will be done through objects and this is a language design principle which is called **Object Orientation**. We can manipulate any class at runtime by defining methods or un-defining them, not only methods but also variables. So think of manipulating any core (built in) class of the language itself like the Fixnum and Integer classes.
Here I will manipulate the Fixnum class at runtime:
irb(main):001:0> 2.concat(8)
NoMethodError: undefined method `concat' for 2:Fixnum
irb(main):002:0> class Fixnum # Open the Fixnum class and add the method
irb(main):003:1> def concat(i)
irb(main):004:2> puts "#{self}" + "#{i}"
irb(main):005:2> end
irb(main):005:1> end
=> nil
irb(main):006:0> 2.concat(8) # Call it again on a fresh Fixnum number
=> 28 # It works!
In the above example you can see that we defined the "concat" method which concatenates a number to the number we called it on. The method become available once we defined it and we can un-define it very simply:
irb(main):007:0> class Fixnum # Open up the method again
irb(main):008:0> undef_method :concat # And remove the method
irb(main):009:0> end
=> Fixnum
irb(main):010:0> 2.concat(8) # Try to call it
NoMethodError: undefined method `concat' for 2:Fixnum
Also we can do this on any built-in method like the `next` method:
irb(main):001:0> 4.next
=> 5
irb(main):002:0> class Fixnum
irb(main):003:1> def next
irb(main):004:2> puts "Some Text!"
irb(main):005:2> end
irb(main):006:1> end
=> nil
irb(main):007:0> 4.next
Some Text!
=> nil
**Note:** You may have noticed that we’re not saying `return` anywhere in the body. That is because in Ruby, methods always implicitly return the value of their last expression. You could of course always jump out of a method by using return before reaching the last statement, but you don’t have to.
Variables
==========
##Global Variables:
Class variables are not available across classes. If you want to have a single variable, which is available across classes, you need to define a global variable. The global variables are always preceded by the dollar sign ($).
##Class Variables:
Class variables are available across different objects. A class variable belongs to the class and is a characteristic of a class. They are preceded by the sign @@ and are followed by the variable name.
##Instance Variables:
Instance variables are available across methods for any particular instance or object. That means that instance variables change from object to object. Instance variables are preceded by the at sign (@) followed by the variable name.
##Local Variables:
Local variables are the variables that are defined in a method. Local variables are not available outside the method. You will see more details about method in subsequent chapter. Local variables begin with a lowercase letter or _.
Symbols
=======
Actually Symbols are just Strings, with an important difference, Symbols are immutable. Mutable objects can be changed after assignment while immutable objects can only be overwritten. Ruby is quite unique in offering mutable Strings, which adds greatly to its expressiveness. However mutable Strings can have their share of issues in terms of creating unexpected results and reduced performance. It is for this reason Ruby also offers programmers the choice of Symbols.
So, how flexible are Symbols in terms of representing data? The answer is just as flexible as Strings. Lets take a look at some valid Strings and their Symbol equivalents.
"text"
:text
"some other text"
:"some other text"
Many Ruby programmers think that Symbols can only contain alphanumeric characters, however by using quotes you can not only use the same characters as you would a String, but also interpolate Symbols as well. The only thing that a Symbol needs syntactically is a colon : prepended.
"hello world#{bang}" # => "hello world!"
:"hello world#{bang}" # => :"hello world!"
There is also an important difference between Symbols and Strings. See this example:
irb(main):001:0> "text".object_id # object_id returns Ruby's internal identifier for an object.
=> 12152780
irb(main):002:0> "text".object_id
=> 12141660 # a new object on the memory (heap).
irb(main):003:0> :text.object_id
=> 110888
irb(main):004:0> :text.object_id
=> 110888 # the same literal refers to the exact same Symbol object.
Conditionals
===========
if conditional then
code..
elsif conditional then
code..
else
code..
end
if expressions are used for conditional execution. The values `False` and `nil` are false, and everything else are true. Notice Ruby uses `elsif`, not `else if` nor `elif`.
Executes code if the conditional is true. If the conditional is not true, code specified in the else clause is executed.
An if expression's conditional is separated from code by the reserved word then, a newline, or a semicolon.
Here is an example:
i = 1
if i > 10
puts "i is greater than 10"
elsif i <= 10 and i! = 0
puts "i is less than 10"
else
puts "I can't guess the number"
end
The result will be
i is less than 10
Loops
=======
Loops in Ruby are used to execute the same block of code a specified number of times. In this section I will cover some of the keywords used to do loops in Ruby.
### while Keywrod:
while conditional [do]
code
end
Executes code while conditional is true. A while loop's conditional is separated from code by the reserved word do, a newline, backslash \, or a semicolon ;.
Example:
i = 0
while i < 3 do
puts "Line number: #{i}"
i += 1
end
This will produce the following result:
Line number: 0
Line number: 1
Line number: 2
###until Keyword:
until conditional do
code
end
Executes code while conditional is false. An until statement's conditional is separated from code by the reserved word do, a newline, or a semicolon.
Example:
i = 0
until i > 2 do
puts "Line number: #{i}"
i += 1
end
This will produce identical result:
Line number: 0
Line number: 1
Line number: 2
###each Keyword:
(0..2).each do |i|
puts "Line number: #{i}"
end
You can see this expression `(0..2)` which is a Ruby way to create range of integers. This code will produce also identical result:
Line number: 0
Line number: 1
Line number: 2
Embedded Ruby
=============
Embedded Ruby or for short *eRuby* is a [templating system][6] which allows to easily embed Ruby code within a pair of `<%` and `%>`. Any code inside this delimiters are then evaluated in-place and replaced by the result of their evaluation. Here is an example of its usage:
<ul>
<% 4.times do |i| %>
<li>list item number: <%= i + 1 %></li>
<% end %>
</ul>
You can see from the above code that eRuby make it easy to generate some list items dynamically. Each list item will have a relevant line number printed and that is done by evaluating the `i + 1` expression (we incremented the number by 1 as it's starting from 0), so we used `<%=` instead of only `<%`.
If you wish to add a comment to any eRuby code you can make it simply with `<%# comment goes here %>`
----------
What is Rails
=============
Rails is one of the most powerful and very popular frameworks for building dynamic web applications. The list of sites using Rails goes on and on. Rails is 100% open source, it is licensed under MIT license, it is free to download and use. Rails is well known for making the developer life easier, it offers a lot of handy features, and forces the development to follow the best practices. It do that by using a lot of common software engineering paradigms and patterns such as the well-known **convention over configuration** paradigm to software development. Convention over configuration means that the developer don't need to write configurations for everything or deal a lot with them, developer just use the conventions that Rails forces, which makes his/her life easier and free his mind from the hassle of configuring everything. It also use the **Don't Repeat Yourself** principle, in which the information must be in a single unambiguous place. One of the most greatest features of Rails is the support for the **Active Record** pattern, which is an approach to access database data. In Rails the *table* is represented as a *class*, each *row* is an *object* of that class, when the object data is updated the corresponding cells in the database are updated.
Rails Architecture
================
Rails is based on the popular architecture pattern Model-View-Controller or for short (MVC) that consists of three building blocks:
- **Models**
Are your business objects describing the structure and behavior of the problem your application is trying to solve. These are usually backed by an Object-Relational-Mapping framework that persists your objects to a database in the background. As I stated in the above section, Rails supports the Active Record pattern so you application data will be represented as objects. The model also notifies its associated views and controllers when there has been a change in its state. This notification allows the views to produce updated output, and the controllers to change the available set of commands.
- **Views**
Are the templates that render data to the user and all the logic surrounding presentational aspects of your application. In the views you can use the above mentioned eRuby for writing templates, that generate HTML pages.
- **Controllers**
Sits at the heart of everything, processing requests from clients, initiating changes in the models and triggering the rendering of the templates.
Here is a simple diagram explaining the relation between these building blocks.
![MVC Architecture][7]
What you have learned so far
============================
After reading this tutorial you now know the basics of the Ruby language and the Rails framework, we will explain how to start writing applications using Ruby on Rails in the next tutorial, from the start to end.
----------
[1]: https://rubygems.org
[2]: https://github.com/postmodern/chruby
[3]: https://github.com/sstephenson/rbenv
[4]: http://rubyinstaller.org/
[5]: http://rubygems.org/pages/download
[6]: http://en.wikipedia.org/wiki/Web_template_system
[7]: http://upload.wikimedia.org/wikipedia/commons/thumb/a/a0/MVC-Process.svg/200px-MVC-Process.svg.png
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment