Professional Documents
Culture Documents
Ruby on Rails
The Basics
by Jamie van Dyke
Fear of Fish
View Code
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.
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
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:
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:
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.
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
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:
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?
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.
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.
So we no longer get a nil object returned (yes, nil is an object too), we get
given our string.
This shows you the ability to mix in (another term for what we just did)
methods to a class.
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
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
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.
Class Variables
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.
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:
You can create a string from another method by calling the .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.
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
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.
You can also access the values of the array in multiple ways.
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.
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).
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.
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.