You are on page 1of 21

Introduction to Ruby on Rails

Ruby on Rails
The Basics
by Jamie van Dyke
Fear of Fish

Introduction to Ruby on Rails 1


Introduction to Ruby on Rails

What is Ruby on Rails


Ruby on Rails is a web framework that rapidly increases the speed you
can create web applications. Rails is opinionated software, meaning it
leads you in the right direction to creating beautiful and maintainable ap-
plications by making it difficult not to.

Introduction to Ruby on Rails 2


Introduction to Ruby on Rails

The General Process


As a request comes in from the browser, the url gets directed to the corre-
sponding controller and action.
Once the application has performed the data operations from the control-
ler action (in this case ‘show’) control is passed back to the views which
render the data given in which ever markup language is chosen, which is
usually html. The id parameter is optional, but in our example is required
because we are showing one particular user, not all users.
Rails makes this roundtrip as easy and powerful as possible.

The General Process

Introduction to Ruby on Rails 3


Introduction to Ruby on Rails

View Code

Introduction to Ruby on Rails 4


Introduction to Ruby on Rails

MVC - Model View Controller


Rails is built on the model-view-controller design principle. This sepa-
rates business logic from view logic and connecting glue code. (controllers)
The pieces are split to make your thought process more natural too, con-
sider the following breakdown:

Model Actual pieces of your application e.g. User, Project, Photo


Relationships are modeled between these pieces. e.g. A User
may be allowed to have many Projects or Pho-
tos. The Rails library that deals with this is Ac-
tiveRecord, you will become intimately knowl-
edgeable with this library if you deal with user
data.
View These are the pieces that your user actually sees e.g. users in-
formation, shopping cart, project details or
maybe an image. The Rails library that handles
views is aptly called ActionView.
Controller Glue code is the heart of your application mapping the url pa-
rameters to actual methods (a.k.a actions)
within your controller. Controllers instruct
models to perform duties on themselves and
coordinate information between them. Data is
prepared for view in the controller and placed
in variables that the view can access for dis-
playing information. Not surprisingly, Action-
Controller is the corresponding Rails library.

If you dig into the Rails source code you’ll find that ActionView and Ac-
tionController are closely related to each other, in fact so much so that
they are distributed together as ActionPack.

Introduction to Ruby on Rails 5


Introduction to Ruby on Rails

Folder Structure

Rails Application Folder Structure

Within a rails application folder most of your time will be spent within the
/app folder, with these tasks:
When you create a model (e.g. User, Project, Photo) it will be places within the /app/
models directory in a file corresponding to the
model name (e.g. user.rb)
When you create a controller (e.g. UsersController) it will be placed within the /app/
controllers folder with a filename that matches
the class name (e.g. users_controller.rb)
When you create a view for an action within your controller (e.g. show) the corre-
sponding rhtml file (Ruby HTML) will be
placed in /app/views (e.g. show.rhtml)
When you want to consolidate helper code that you are re-using multiple times in dif-
ferent views, you will place the code within the
/app/heleprs folder

Introduction to Ruby on Rails 6


Introduction to Ruby on Rails

A Deeper Look at our Example


When you come to think how your application idea will fit into the
Model-View-Controller design, you’ll start to separate pieces of the plan
in your head and will start to see the models that will form the basis of
your application. If we assume we have an application that will manage
user data, we would immediately assume we will have a User model.
Rails favours convention over configuration which mean it expects your
application to be planned a particular way, once you’ve learnt the basics
of this you’ll be able to assume lots about classes and helpers you’ve never
used because it fits into this convention. Most importantly to us at the
moment is directory structure and file placement which we looked at in
the last section. Rails has a skeleton structure when you first create an
application, and within that structure it has places for your models, views
and controllers to go.

Let’s say we’re creating an application that will store information on indi-
vidual users, a social networking site of course! We need a model, view
and controller like the following:
The User model will hold our user information.
./script/generate model User
will produce /app/models/user.rb which will look like the following:

Our User Model

We will generate a controller to manage this information


./script/generate controller Users
will produce (among other things) an /app/controllers/users_controller.rb
which you need to adjust to look like the following:

Introduction to Ruby on Rails 7


Introduction to Ruby on Rails

Our Users Controller

We need to generate a view to show our user data, this can be done in a
number of ways, let’s focus on showing one user.
Create a file called /app/views/users/show.rhtml with the following code
within it:

Our Show View

The code is fairly self explanatory, the controller asks the model (User) to
find the user with an id (in the database) of params[:id]. params is a vari-
able in rails that corresponds to whatever the browser asked for, either a
GET or a POST request. In our case a get request which in our example
earlier (http://www.example.com/users/show/1) means an id of 1. The
controller puts the returned value (from the model User) into an instance
variable (@user) and the view uses that to access the information. This
example relies on you having a database with a users table which the
model will access.

Introduction to Ruby on Rails 8


Introduction to Ruby on Rails

Class Basics
Ruby is an object-orientated language. This means that everything you
interact with is an object, and you send it messages telling it to perform an
action or give you a value. The messages you send to an object will be
picked up by methods that you create.

Declaring a method

Above we declared a method called “hello”, let’s define it in a class:

Creating a class with a method

Classes are the factories for our objects and by convention they are cre-
ated with a capital letter, we create an object from a class by instantiating
the class, which gives us an instance. Let’s create an object from our class
above and then call the hello method and see what happens:

Creating and calling a method on our new class

So now we can see how to create a new object from our classes, and how
to call a method on that instance of it. We were returned nil, what’s that?

Introduction to Ruby on Rails 9


Introduction to Ruby on Rails

Well it’s nothing, and we were returned that because we clearly didn’t do
anything within the method itself. If we were to put some code within it
and return a value, we’d be given something back. Let’s change the
method so it gives us back a string.

Making our method do something

The return keyword passes back something from the method and ends
execution at that point, so anything beneath it will not be run unless you
were within a loop or conditional statement (more on that later). Now if
we create an instance of this method and call the hello method, we’ll be
given back the string.

Our new object at work

So we no longer get a nil object returned (yes, nil is an object too), we get
given our string.

Introduction to Ruby on Rails 10


Introduction to Ruby on Rails

Ruby Module Basics


Modules are a powerful piece of kit, and they are used extensively in
Rails so understanding them is very important, I recommend doing extra
reading once you’ve completed the training session.
Ruby supports inheritance, meaning a class can have a parent class which
it inherits all its methods from. Some languages support multiple inheri-
tance, which pardon my pointing out the obvious, inherits from multiple
parent classes and has access to all their methods. Ruby isn’t on of those
languages, instead Ruby let’s you create modules which are a grouping of
methods that you can include in a class and thus have access to those
methods.
Let’s take our earlier class and add a new method to it from within a
module. You’ll see this in plugins heavily within Rails.

Adding methods to a class with a module

This shows you the ability to mix in (another term for what we just did)
methods to a class.

Introduction to Ruby on Rails 11


Introduction to Ruby on Rails

Ruby Variables
A variable is a word programmers use for a container, a way of storing
information for later use. If we wanted to calculate 4 x 100, and use it
later on where would we hold it? The answer is a variable. Variables
come in a few flavours, each one is visible to a different degree within
your application. If variables were always available everywhere and at
anytime, memory usage on applications would rise and your server would
not be a happy bunny.
Ruby variables are what we call untyped, this means that if you put a
string in a variable like the examples below, your variable becomes a
string. However, if you immediately afterwards put an integer into the
same variable, it will cease being a string and become an integer instead.
The values and type of a variable are overwritten when a new value is
placed within it.

Local Variables

Declaring a local variable

Local variables are created using a simple lone word, and any subsequent
words are separated by underscores (by convention), and they are avail-
able only within the context they are called.

Instance Variables

Declaring an instance variable

Instant variables begin with an @, and they are available within the con-
text of the class rather than the method, so once the method has com-
pleted the instance variable is still available. These also happen to be how
Rails passes information from the controller to the view.

Introduction to Ruby on Rails 12


Introduction to Ruby on Rails

Class Variables

Declaring a class variable

Class variables begin with a @@, they specialize in connecting between


different scopes within classes. Scopes are a special term for declaring
the visibility of a variable and example would be private, which would hide
the methods from being called from outside the class.

Global Variables
Global variables are available everywhere within your application, but
please note that the use of globals is frowned upon in any language as
they are bad programming practise, they are for emergencies.

Introduction to Ruby on Rails 13


Introduction to Ruby on Rails

Strings
Ruby has a few built-in class methods that you will use regularly. A
string can best be described as a grouping of characters, whether it be 1
letter, or a string of characters. All Ruby classes come with their own
methods that provide you with the majority of operations you will need to
execute on that class.
Here are some string examples:

Examples of methods on strings

You can create a string from another method by calling the .to_s method

The built-in to_s method

I won’t go into detail here, but if you need a class you have built to return
a specific string when .to_s is called, you can override it by merely defin-
ing a to_s method in your class. Overriding methods of any superclass
(parent) works in this way. In this case you are overriding the Object
class method, which all classes will have as a superclass.

Introduction to Ruby on Rails 14


Introduction to Ruby on Rails

Symbols
A symbol is a string but faster, and without all the whizzy string manipu-
lation functions (how could it have them, it’s not a string!). Symbols are
smaller in memory footprint and faster (ruby uses them internally too)
than strings, and for this reason they’re usually used as hash keys (more
on that later). Use a symbol if you need to store the name of something
or label an item, for example a hash key like I just said...I don’t always
repeat myself this much.

Examples of symbols

A symbol begins with a colon and is followed by a lowercase and/or un-


derscored word.

Introduction to Ruby on Rails 15


Introduction to Ruby on Rails

Arrays
An array is an ordered collection of objects, think of it as a queue. Any-
thing you add to the array will be added to the end of the queue unless
the position you’re adding it to is explicitly stated. There are a few ways
to create an array.

Creating an array of strings

You can also access the values of the array in multiple ways.

Arrays are used throughout Rails and other Ruby scripts/applications


quite regularly, in fact most functions in Rails which return more than
one value will return an array of values.

Introduction to Ruby on Rails 16


Introduction to Ruby on Rails

Hashes
A hash is an unordered collection of objects. Instead of accessing the val-
ues of a hash from a particular index number, like an array, you access a
value by using a key (a key/value pair is the technical term). All keys
have a corresponding value, and all values have a corresponding key.
You’ll often see symbols used as hash keys because of their higher effi-
ciency.

A hash with symbols as the keys

Hashes and arrays can contain hashes and arrays, these become multidi-
mensional hashes and arrays, now try and say that after a few drinks (dis-
claimer: unless you’re under the legal drinking age of your country).

Introduction to Ruby on Rails 17


Introduction to Ruby on Rails

Iterators and Blocks


Iterators are methods that execute something one or more times. One of
the most common iterators is each, which you would use to call a block of
code on each element within, say, an array.

Examples of iterator usage

The example shows two different ways to call a block. The first is an in-
line block which uses curly braces to denote the block, and the second
uses the do keyword with an end. Also highlighted in this example is how
we insert a value directly into a string with the #{} syntax.
Blocks are special constructs that are passed a value by the method, in
this case each value from the array is passed into the block and I use puts
to output the value to the console. I recommend reading more about
blocks in either the Ruby Pickaxe book or Ruby for Rails by David
Black.
Using iterators in views is a good example of how you can use iterators
and code blocks to do something for each value within, say, an array of
database results.

Introduction to Ruby on Rails 18


Introduction to Ruby on Rails

Iterating over a users array in a view

Here we’ve iterated over each user in the users array, and for each one
we’ve drawn up a div block. Within the code block you can see that
we’re able to call methods on our object and output them to html.

Introduction to Ruby on Rails 19


Introduction to Ruby on Rails

Introduction to Ruby on Rails 20


Introduction to Ruby on Rails

Note: This is still a work in progress, there is more on Rails itself to be


included once I have a more solid plan on which bits are the most impor-
tant.
I’d like to thank David Black for his permission to reference his work-
shop handout from http://rubypowerandlight.com and his input on lots of
matters. For those looking to move on with Ruby or Rails from this
training session then I highly recommend David’s Ruby for Rails book
which is available online through all major retailers.

Introduction to Ruby on Rails 21

You might also like