Advertisement
Ruby

Learn Ruby on Rails from Scratch: Week 2

by

Welcome to Ruby on Rails From Scratch Week 2. Hopefully this sequel to week 1 will help to further your education in Rails. This week, we'll do a little bit more with getting an actual page up and running. We'll also work on adding more interactivity by embedding ruby in HTML and learning a little about variables. After that, we'll learn more about Ruby's beautiful URL structure and how to manipulate it, plus other things as well. This is definitely going to be a packed week!

Last Week...

Last week, we got the framework set up, and learned a little bit more about ruby and rails. We then learned how to create a new application and generate a controller.

Ruby Editors

Now that we're going to get into Rails Syntax, we need a good editor. Since rails is a relatively new framework, it doesn't have quite the range of syntax supported editors. Luckily, there are still extremely good ones out there. For windows, I personally use E Texteditor. It has great support for ruby, and features automated scripts for many languages. E text editor branched off of the success of the exclusive mac program TextMate. The only downside to both, are that they aren't free. If you're looking for something free, you could always go with the reliable Notepad ++.

Getting Things Visible

Creating an Action

As you might remember from last week, we ended by creating a controller which we called learn. This will lead us into today's tutorial. We are now going to use that controller, and create an action in the controller. We will then also create a corresponding view file. The view is the component of MVC architecture that usually contains all of the HTML, and therefore is an embedded ruby file (rhtml).

Now that we have the learn controller generated, we can view the rb file by going to app/controllers/learn_controller.rb. Right now, you should see the following code already there:

controller start

This default code allows this controller to inherit the default application controls.

We now need to define a method, specifically, an action. This action will map out the URL for the view. To define an action named more, we type the following code:

def view

We can pick any name we want. A good strategy when picking the name of the action, is giving it a name that has to do with the content that will be there. You should also pick the name according to the desired URL. The controller and action map out the URL. For example, to get to the "more" page, you would type in, localhost:3000/learn/more. In fact, let's try it and see what happens:

missing template

Oops...as you can see from the helpful error message, we still need to make a view.

Creating a View

Unlike the controller, to create a view we do not need to generate it through the console. Instead, we can simply create a new file. When we generated the controller, learn, you might have seen that a directory (called learn) was created in the app/view folder. We need to create an .rhtml file inside there, and call it the action that we defined in the controller.

A picture's worth a thousand words, so here you go:

view more

And now, just to test out the page, we'll add a little HTML and see what happens. I just added a basic required HTML, and then some dummy text and title. You can put anything you'd like here.

HTML skeleton

Save it, and lets test it out again.

test

Great it works! Congratulations, you created your first page in Rails. Although it's not much now, you now have a basic understanding of how to create a basic rails application.

A Note

Ruby on Rails has some paradigms that it follows. For example, normally, when you are building an application in rails, when you generate a controller, you capitalize it and make it singular. Although we didn't capitalize the current controller we are working with, it is a good habit to get into when you are building real applications. I remember when I was learning Rails for the first time, it frustrated me that all of the tutorials I read, mentioned a paradigm here and there, but never listed all of them in one place. I don't want to do the same to you! But, if I explained them all now, it wouldn't sink in as well, as if you knew more about each component. So don't worry about it too much now, and I'll explain it later in this series.

Adding Interactivity

Review

Last week, we learned how to embed rails code into an rhtml file. If you remember, a <% -%> is processed code, but doesn't include anything that will actually be outputted to the user. On the other hand, <%= %> code will be outputted.

Math Time

You can do math easily with ruby. For this example, I created a new action in the learn controller called math. We are going to do some simple math which will be embedded in tags above. Here is what we will type:

<html>
<head> <title>Math Demo</title> </head> <body> Will it output 4 +5, or 9?<br /> <%= 4 +5 %> </body> </html>

As you can see, it did the math for us:

math

String Concatenation

You can create a string in ruby by using quotes. You can even combine strings together by concatenating them together. There are several ways to do this. The most logical, is to treat it like math:

<html>
  <head>
  <title>String Demo</title>
  </head>
<body>
    
  <%= 'This is kind of boring' %><br>
  <%= 'Will I combine' + 'With You?' %>
  </body>
  </html>

When we output this we show how exact ruby is though. Notice there is no space between combine and with. To add a space just add one before the quote at the end of combine or before with.

hello world

How Important is the = and - sign?

They are both very important. I mention this again, so you clearly get their purpose. The equal sign determines if the user sees it or not. If we were to revisit that last bit of code and take out the equal sign from both of the snippets, we would just have a blank page. Now, if you are assigning a variable or something that doesn't physically output anything, then don't put the = sign,

The - sign is not necessary, but a good habit to get into. If you're not using the = sign, then put a - sign, when you're closing the embedded ruby. This eliminates the white space that would otherwise be inserted into the code. This can, in very rare cases, mess up the project.

Variables

We cannot go any further without discussing variables. For those that have no experience with Javascript, or any server side language, you might not know what exactly a variable is. Think of a variable as something that stores a little bit of information. You can then analyze this data and manipulate it by calling it by its name.

Assigning A Local Variable and Displaying It

Assigning a local variable is quite easy. Here is how you would assign it and then display it. You could do this in one line, but I'm showing the difference between embedded processed ruby and embedded and shown ruby (The equal sign thing again :) ):

<html>
  <head>
  <title>Variable Demo</title>
</head>
<body>
    
  <% text = 'This is a Variable' -%>
  <i><%= text %></i>
  </body>
  </html>

And here you can see the result:

variables

Assigning An Instance Variable and Displaying It

The problem with local variables, though, is that they're...local. What if we need to assign a variable in the controller, and display it in the view? That's where instance variables come in. An instance variable is set apart from a local variable by the @ sign which is put before the name. Please note that both instance and local variables (as well as most other kinds) cannot have capital letters and no spaces.

To demonstrate how we can pass dynamic content between the controller and view, we will first have to insert code into the learn controller. By now I have added more definitions for all of the above demos. Here is the current learn controller. As you can see, I have assigned an instance variable in the variables action. When the user requests that action, Rails looks up the definition, processes it, and sends it to the view (In this case, the value of the variable):

class LearnController < ApplicationController
	
	def more
	end
	
	def math
	end
	
	def strings
	end
	
	def variables
		@text = 'Why Hello'
	end
	
end

Now we're going to reference the variable in the view:

<html>
  <head>
  <title>Variable Demo</title>
</head>
<body>
      <i><%= @text %></i>
  </body>
  </html>

Sure enough, the variable is passed to the view.

variables

 

Next Week and Final Words

This week we learned about setting up actions in controllers, defining views, local, and instant variables. I hope that you found it all helpful! Next week, will be even more exciting. I plan on finishing up the basics of the interaction of the controller and view. Hopefully we will also have time to learn more rails techniques too! After that, it just gets more exciting! (Ruby syntax, working with databases, scaffoldings, etc.). Anyway, if you have any questions, be sure to let me know; and I'll be sure to get back to you!

Like always, please Digg this if it helped you!

  • Subscribe to the NETTUTS RSS Feed for more daily web development tuts and articles.


Related Posts
  • Web Design
    eCommerce
    Taking Shopify Theme Development FurtherShopify thumb
    In this final part of our Shopify series we will look at how a deeper knowledge of Liquid will enable you to make your themes even more flexible. This will help you deliver richer and more imaginative store designs.Read More…
  • Code
    PHP
    Creating a Photo Tag Wall With Twilio Picture Messaging & PHPProcedural to oop php retina preview
    Twilio's recently announced Picture Messaging has vastly opened up what we can do with text messaging, now we can attach photos to our text messages and have them get used in different ways. In our case, we are going to build a Photo Tag Wall, which will contain photos linked to tags that will be displayed on a website.Read More…
  • Code
    Ruby
    Writing Robust Web Applications - The Lost Art of Exception HandlingRails education retina preview2
    As developers, we want the applications we build to be resilient when it comes to failure, but how do you achieve this goal? If you believe the hype, micro-services and a clever communication protocol are the answer to all your problems, or maybe automatic DNS failover. While that kind of stuff has its place and makes for an interesting conference presentation, the somewhat less glamorous truth is that making a robust application begins with your code. But, even well designed and well tested applications are often lacking a vital component of resilient code - exception handling.Read More…
  • Code
    Articles
    Coding With KodingCoding with koding retina preview
    Cloud IDEs have been around for a little while now, and they have been pretty good for things like pair programming, or cases where you want to code consistently no matter where you are. Koding just came out of private beta, and they would like to take this notion a couple steps further, with their "cloud ecosystem". In this article we will take a look at what Koding is, as-well as some of the benefits you can get from using it.Read More…
  • Code
    JavaScript & AJAX
    Introduction to Sails.jsSails preview 400 2
    Sails is a Javascript framework designed to resemble the MVC architecture from frameworks like Ruby on Rails. It makes the process of building Node.js apps easier, especially APIs, single page apps and realtime features, like chat.Read More…
  • Code
    Scala
    Building Ribbit in ScalaRibbit scala retina preview
    In this tutorial we will implement the Ribbit application in Scala. We'll be covering how to install the Play web framework, a NetBeans plugin for it, and finally the code in Scala. If you are new to Scala, check out this previous tutorial which will help you set up your environment and provides you with a general platform that you can build upon. Even though the essence of Ribbit is to create/send/read Ribbits (our version of tweets), we will spend a large part of this tutorial explaining how Play works, authentication, and persistence. After these are in place, the rest becomes much easier. We will also implement ribbit creation, submission and listing out all ribbits. Following someone, advanced user settings, and direct messages will be an extra assignment for you to complete on your own. I am sure if you manage to follow along with this tutorial and create Ribbit as explained below, these three functionalities will be easily accomplished as homework.Read More…