Chapter 10. Real-World Applications: Rails in the real world

image with no caption

You’ve learned a lot about Ruby on Rails.

But to apply your knowledge to the real world, there are a number of things you need to think about. How do you connect your application to another database? How do you test Rails apps? How do you make the most out the Rails and the Ruby language? And where do you find out the latest on what’s happening with Rails? Keep reading, and we’ll put you on the inside track that will take your development skills to the next level.

image with no caption

All of the techniques you’ve learned so far ARE useful... but there’s more to learn.

Yes, it’s true. Things out in the world don’t always go the way they should. Not only that, but Rails is a pretty big framework. There’s more than this book, or any other book less than a few zillion pages, could ever hope to cover.

But there’s no reason to assume you’re not prepared! Skim through these last few pages to see what you know, and even pick up a few more tips on things you don’t.

Geek Bits

To find out more about the helpers that are available in the current version of Rails see http://tinyurl.com/railshelpers

Look! It’s a big Ruby “Try this” page

Did you notice how little Ruby you had to know in order to develop cool Rails web apps? Even so, knowing a bit more Ruby can sometimes be useful. Here are some sample bits of Ruby you might want to experiment with. Just type them in and see what happens...

Try This!

Read the lines of a file into an array called “a”

Create a string with 50 =-signs

a=File.readlines("filename.txt")
"=" * 50

Sort an array

Get an array of words from a string

a.sort
"to be or not to be".split

Reverse a string

Return the class (datatype) of an object

"Bass ackwards".reverse!
o.class

Return a copy of a string that is reversed

Round a Float to the nearest whole number

"Bass ackwards".reverse
(3.14).round

Does the String s contain “Waldo”?

Find a square-root

/Waldo/ =~ s
Math.sqrt(16)

Is the String a zip code?

Delete a file

/^d{5}$/ =~ "90210"
File.delete("filename.txt")

Converting a string to a Fixnum

The current date and time

"12345".to_i
Time.now

Convert a String to a float

The current year

"3.1415".to_f
Time.now.year

Convert an object to a string

Give a method another name

a.to_s
alias my_method

Pretty-print the contents of an array

Return an array of files in a directory

[1, 2, 3, 4, 5].inspect
Dir.entries("directoryName")

Pretty-print the contents of an array

 
{:a=>1, :b=>"c"}.inspect
 

Web apps need testing too

Automated testing is one of the most important parts of software development, and yet until now, we haven’t mentioned it. So why not? Testing a piece of software relies on a thorough understanding of the tools you are using, and designing tests can be far more difficult (and enjoyable) than writing the code itself. That’s why this book has concentrated on giving you the skills to understand how Rails works and thinks. Only once you understand that can you start to think about how you will test applications.

But that doesn’t mean that you do testing long after you have finished writing a system. Far from it. The best tests are written before you write your main code.

Note

For more information, see “Extreme Programming Explained,” ISBN-13: 978-0321278654.

Rails comes with a ton of testing support, far more than almost any other framework. Every application contains a set of test scripts (in the test directory), and every time you generate scaffolding, Rails also generates a set of standard tests for you. So, if you go into the folder where you wrote the scaffolded tickets application in Chapter 1 and type:

image with no caption

Rails will run a whole suite of tests for you. Does that mean that you never need to write your own? Actually, no. A lot of your time as a Rails developer will be spent writing and maintaining tests.

So what kinds of tests are available?

There are three main types of test:

Unit tests

Rails sometimes uses terms that are not quite the same as you’ll find elsewhere. In most systems, a “unit test” is a test of any standalone piece of code. But Rails is more specific than that. In Rails, a “unit test” means a test of a model class. Rails creates standard unit tests for you in the test/unit directory whenever you generate a model either directly, or via scaffolding.

Functional tests

What Rails means by a functional test is a test of an individual controller. Functional tests check that if you make a particular kind of request, you get a particular kind of response. You can find functional tests in test/functional. Again, Rails creates functional tests whenever you generate controllers, either directly or via scaffolding.

Integration tests

This are high-level tests that read a little like the sort of test-scripts that manual testers use. Integration tests test the system as a whole. So they automate the set of actions that a typical user might perform on your system. There is a special folder for integration tests (test/integration), but they are not generated automatically. They are very specific to what you need your system to do and so you need to create them yourself.

Finally, the test data for all of these tests is stored in data files in test/fixtures. A fixture is just a fancy name for a set of test data. Rails will store the data from the fixtures in a special, separate test database to make sure that your development (or live data) does not get mixed up with data required for your tests.

For more information on testing in rails see http://tinyurl.com/railstest

Going live

Your application won’t stay in development all its life, and at some point, you’ll need to send it live. So what do you do then? It’s not a good idea if your application has code in it that specifies the location of the database and so on. After all, you don’t want the live and test versions of the code to do different things. You just want them to use different databases.

That why Rails lets you specify environments. An environment sets the location and type of your database as well as a few other settings, such as how log messages will be recorded.

By default, an application is set up to use three different environments:

  1. development

    This is the environment that is used by default. It’s the environment that we have been using all the way through the book. The development environment uses the db/development.sqlite3 database.

  2. test

    This environment is set aside for the use of the automated testing scripts.

  3. production

    This is your live environment.

But how do you switch between environments?

When you start the server, Rails looks for an environment variable called RAILS_ENV. This will tell it which environment to run. If you want to switch from the development enviroment to the production environment, you need to set the RAILS_ENV variable:

image with no caption

So how do you change the database?

If you look at the config/database.yml file, you will find the database details for each environment.

For example, your original SQLite production environment might be set like this:

image with no caption

But if you wanted to change the production environment to use an Oracle database, it would probably look something like this:

image with no caption

Or, if you want the live environment to use a MySQL database hosted on the same machine as Rails, you would change it to:

image with no caption

What’s REST?

We’ve heard a lot in this book about REST. How Rails uses REST. How REST design is the new guiding principle of Rails. How if you use REST, your teeth will be brighter, your life will be happier, and all will be goodness and sunshine with the world.

Let’s start with the basics. REST stands for Representational State Transfer, and it’s a way of structuring how people work with computer systems. Obviously, the most important computer system around is the World Wide Web, and it’s significant that the guy who came up with REST—Roy Fielding—was also one of the authors of the HTTP spec.

So why does it matter that the HTTP guy is also the REST guy? Well, because RESTful design really means designing your applications to work the way the web was originally meant to look.

So what are the main principles of REST?

  1. All the important stuff is a resource.

    What this means is that all the important data in your system is separately identifiable things that you can do stuff to. If you have a web site that sells donuts, then the donuts are resources.

  2. Every resource has a proper name.

    On the web, this means that everything has a URL.

  3. You can perform a standard set of operations on the resources.

    The CRUD (Create, Read, Update and Delete) operations are a fairly typical set of operations, and they are supported by Rails and the web.

  4. The client and server talk to each other statelessly

    This means that when a client (like a browser) talks to a RESTful application, it is as a distinct set of requests and responses. The client talks to the server. The server answers. Then the conversation ends.

All of these things seem pretty obvious, don’t they? They are a pretty good description of how the web works.

And they were a good description of how the web worked. Before it went wrong...

The web application that went astray

Imagine there was a web application that allowed somebody to sell spare parts for rockets:

They might create a system that displays a rocket component like this:

http://www.boosters-r-us.com/airframes/472

The web site is about rocket components and this is a URL that can be used as the name of the component.

But look at what happens when someone updates the details of the component, like—say—its price. The web form in the system submits the details to this URL:

http://www.boosters-r-us.com/airframes/472/update

The trouble with this is it’s not RESTful. Why? Well URLs in a RESTful system are supposed to be names of resources. And this second URL doesn’t represent a thing it represents an action.

Why is not being RESTful a problem?

Have you ever revisited a URL in your browser and been asked if you want to repost data? The browser history is just a list of URLs and that should mean that it is a list of names. But if a web application uses URLs that represent activities then when you go back through your history, the browser won’t know whether you intend to redo the actions.

HTTP verbs are the only verbs you need

But how do we get around this problem? The third principle of REST says that there should a well defined list of actions available. A RESTful application uses HTTP methods to define the activity and leaves the URL to name the resource:

image with no caption

Living on the Edge

Rails is changing all the time, but how will you stay up with all the latest and greatest features that have been added? One way is to run on the Edge.

Rails make it really easy to run on the very latest build of Rails (called Edge Rails) by downloading and installing the latest version of the framework directly into your application.

Now in some other application frameworks, changing to the latest version of the framework would be incredible difficult. You would have go to a web browser. Download the files. Read the latest install instructions. Play with paths Set up the configuration so that it matches your system. And so on. It would be so complicated that very few people would bother.

But lots of people run on Edge Rails. Why? Well it’s not just because they want to use the latest features. Rails is in furious development all the time, and you may find that even a small upgrade might break some piece of your application. So to make sure that their apps will keep working as Rails evolves, they don’t wait for weeks or months to upgrade, some of them update to the Edge every day.

But how do you install Edge Rails in your application? It’s simple. You do this:

image with no caption

That single command is all you need. The rake tool will connect to the Rails development servers and download the latest version of the rails scripts and install them in the vendor/plugins directory of your application. Every time you start the Rails server, the code in the vendor directory is used before going to the main Rails install on the machine. That means that Edge Rails will be used for that single application.

Life can be pretty hairy on the Edge. But sometimes it’s better to find version compatibility issues, one at a time...

Getting more information

Even though Rails allows you to create fully-functional web applications fast and safely, there’s no doubt that to really master Rails can take a really long time. There’s simply so much of it.

This means you need a pretty good reference. And the best references are online. Rails is changing all the time. Every day new things are checked into the Rails source code, and the only way to keep up with it is to go online. Here are some great web sites to get you started:

  1. http://www.rubyonrails.org/

    The home of Rails itself. It’s not only the place for software but also presentations, screencasts and links for further reading.

  2. http://wiki.rubyonrails.org/rails

    This gives detailed instructions on installation and troubleshooting, as well as providing links to further online resources.

  3. http://ryandaigle.com/

    Ryan’s blog contains a wealth of information on the latest cool tricks you can do in Rails.

  4. http://www.ruby-lang.org/en/

    The latest information on the Ruby language.

Built-in documentation

As well as a plethora of online material, your Ruby on Rails contains most of the things you’ll need, right out of the box. The two most important command line tools are:

ri <something>

Where <something> is a Ruby class that you need to know more about. For example, “ri Array” will tell you all about the Array class.

Another source of useful information is through the gem server. Gem is the most commonly used package management tool for Ruby and it is probably the command you used to install Rails. Gem has a built in server that provides the same kind of API documentation you find at the http://api.rubyonrails.org site. To start it type:

gem server

and then open a browser at:

http://localhost:8808/

A little light reading...

Of course, here at Head First Labs, we’re book people. And it’s doesn’t matter how great the online material is, there’s nothing to beat having an actual real book with pages and everything to help you absorb the material. Now that you’ve got to the end of this book, and your brain is feeling fit and full of new Ruby on Rails expertise, you might want to take the chance to try out these other tripendicular tomes:

The Ruby Way

We love this book at Head First. It’s a big, meaty work, but it’s beautifully written by Hal Fulton. This is a book that will take you on a deep journey into the Ruby language. The great thing is that it doesn’t just give you the details of the language, but it also explains the philosophy behind the language design. Many of the things that make Rails so great come directly from Ruby. And many of those things are mentioned in this book.

image with no caption

Agile Web Development with Rails

This is a great book to take you further into Rails development. An interesting thing about it is that it is written like a development project. So a few months before a new version is released, a beta version is released online for people to try out and comment on.

image with no caption

Rails Cookbook

Once you get up and running with Rails, you will probably need to solve the same kinds of problems that many, many other people have had to deal with before you. Fear not! Rails Cookbook gives a you a delicious set of pre-written pieces of code to get you through your difficulties.

image with no caption

Now, as well as books on Ruby and Rails, you might find it useful to read up on the related topics. And what’s the best way to bootstrap your brain in a new subject? With Head First books, of course!

Head First Ajax

Rails comes with a ton of built in support for Ajax development, but to really make the most out of it, you need to get to grips with how Ajax really works. And what better way than with Head First Ajax?

image with no caption

Head First JavaScript

Ajax is built on JavaScript, and if you know in detail how to hack JavaScript, you’ll really make your application sing. Head First JavaScript is a great way into the language.

image with no caption

Head First Software Development

In this book, you’ve learned about how to program in the Ruby on Rails framework. If you want to move from programming to development, then pick up this book. It will teach you how the real pros do it, from how to run the planning in your project, to automated testing and continuous integration.

image with no caption

Tools for your Rails Toolbox

You’ve got Chapter 10 under your belt, and now you’ve added some real world things you need to think about.

Rails Tools

Rails contains a bunch of extra helpers that you can use in your applications

The Ruby language is pretty powerful. While you can create cool web apps without much Ruby knowledge, knowing a bit more Ruby is useful.

rake test - runs the automated tests in your application

rake rails:freeze:edge - installs the latest version of Rails into your application

RAILS_ENV=production - runs your system against a *live* database

ri <something> - gives you information about the methods of a Ruby object

gem server - starts the Ruby documentation server

Your brain - this is most powerful development tool you have

Leaving town...

image with no caption

It’s been great having you here in Railsville!

We’re sad to see you leave, but there’s nothing like taking what you’ve learned and putting it to use. You’re just beginning your Rails journey, and we’ve put you in the driving seat. We’re dying to hear how things go, so drop us a line at the Head First Labs web site, www.headfirstlabs.com, and let us know how Rails is paying off for YOU!

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset