Rails in a Nutshell
Šios medžiagos vertimai:
- into Russian: Rails вкратце. 97% isversti negalutinai. Liko visai mažai, pirmyn!
-
Versti pasiūlė alexbaumgertner 28.10.2009
Paskelbta prieš 10 mėnesiai.
Tekstas
Chapter 1. Rails
What makes you happy?
Programmer happiness comes from being able to quickly and correctly express the ideas you’ve got in your head so it’s easy for another person to understand and build on.
Surprises in code behaviour, having to repeat yourself, chores like filling out configuration files, designing a directory structure convention to keep everything in and finding libraries to do what you need are all common obstacles.
Rails sidesteps these problems by being predictable, following the DRY* principle whereever possible by coming with well-chosen defaults to minimize configuration chores, an easily-navigated file-structure, and bundled libraries for what you’re probably going to be doing with a web application – altogether, the general idea is convention over configuration.
By building an application with Rails, you get to concentrate on your own problem instead of those that have been solved already.
Architecture
After you’ve written a few web applications, you pick up on some patterns about how they’re best built and maintained.
Typically, there are three archaetypical team members working on it: a business person, a designer, and a manager to glue everything together when results need to be delivered. These experts perform better when they have complete control over their own domains, so give them space—separate all their code, and only let them talk to each other through explicitly defined public methods.
This idea of keeping concerns separate when it comes to business logic, presentation, and bringing it all together is formally known as the Model View Controller (MVC) pattern. Rails is built on this idea of separating concerns.
Model
A model contains business logic – whether or not to ship something somewhere, send a happy birthday notification, or launch a space ship. They act as models, or representations of things in real life. These decisions are often made based on past events, so a database is usually involved.
Rails handles the conversation with the database with ActiveRecord, leaving you to just fill in the parts relative to your business. Tests are done through the bundled UnitTest package.
View
A View contains presentation logic, i.e. “what is this going to look like on a browser, or in an RSS reader somewhere?” This is the domain of a designer – they’re given data from a model, and asked to render it somehow so it’s presentable.
Rails delivers presentation logic through ActionView, which comes with
an embedded-Ruby templating language (ERB),
a builder-based templating language (useful for XML content like RSS, or JSON content),
helper methods for form-generation, dates, links, and text,
layout sharing for template reuse
javascript and ajax integration
scaffolding
Controller
Controllers bring everything together. Their job is to respond to an outside request, ask the business logic components to make a decision and return some data, hand it over to a view, and return the rendered results.
ActiveController is the part of Rails that makes this work by giving you
filters for pre- and post-processing responses (useful for things like authentication)
routing (the convention is REST, but it’s easy to adapt to whatever url-system you need)
automatic benchmarking and logging
caching (at three levels of granularity)
session managment
Note
ActionView and ActionController together are known as ActionPack
Mailing
Not part of the MVC pattern (though arguably a presentation layer), you’re probably going to want to send email at some point.
Rails makes that easy by coming with the ActionMailer library which makes email design and delivery really simple.
Candy
Rails also bring with it modifications to the Ruby language that let you write things like
5.days.from_now
This layer of additional syntactic sugar on top of the Ruby standard libraries happens through the ActiveSupport library.
Extensibility
It’s easy to modify Rails to get you to that last step if it doesn’t do it already. For that reason, there are a ton of plugins available.
If installing one of the many out there already doesn’t work for you, we’ll show you how to write one.
An Example Rails Application
Let’s build a simple newspaper web appliction that lets us write, edit, and show articles.
From the command-line, create the Rails project by running rails newspaper
Jump into that directory: cd newspaper
Let’s take a look at what was generated. [insert table of directory structure and description]
Start the application (it comes with its own server that runs on port 3000 by default): script/server
Take a look at it in your web browser by visiting http://localhost:3000
Note
You’ll be needing a text editor for these next parts. If you’re on Windows, that means notepad; not Word.
If everything has gone right, you’ll see a webpage with some suggestions on how to get started writing your app.
Let’s follow the advice and use script/generate to create our models and controllers.
An easy rule of thumb to use when figuring out what an application’s models should be is to look at nouns used when describing what it should do. In this case, this app is supposed to let us write/edit/show articles, so we’ll start with an Article model:
$ ./script/generate model Article
exists app/models/
exists test/unit/
exists test/fixtures/
create app/models/article.rb
create test/unit/article_test.rb
create test/fixtures/articles.yml
create db/migrate
create db/migrate/20090913163814_create_articles.rb
We’re also going to need a controller for when readers want to read the articles:
$ ./script/generate controller articles
exists app/controllers/
exists app/helpers/
create app/views/articles
exists test/functional/
create test/unit/helpers/
create app/controllers/articles_controller.rb
create test/functional/articles_controller_test.rb
create app/helpers/articles_helper.rb
create test/unit/helpers/articles_helper_test.rb
Warning
Controller names are conventionally the plural of the model they control, so make sure you typed articles, and not article. If you stick to this naming convention, Rails gives you a few things for free like automatic routing, which we’ll cover in a bit. If you did mess up, run script/destroy controller article
Now that we’ve got a controller and a model, let’s take a look at the app again. Start up script/server if you had shut it down, and point your web browser at http://localhost:3000 again.
Looks like nothing has changed. It’s because we haven’t done step 2 – “set up a default route and rename this file”. The file referred to is in public/index.html.
The public/ directory is where all static files like Javascript, CSS, and images live. Try testing it out by editing public/500.html to say that you like cake by changing We're sorry, but something went wrong. to We're sorry, but something went wrong. But I do like CAKE! and visiting http://localhost:3000/500.html – if the message didn’t change, restart the rails server and try again. (This is a debugging technique you should always try first.)
Now that we know how the public/ directory works, we know that the page we were looking at before really is public/index.html, and that’s going to get in the way of every request to http://localhost:3000/ because web servers default to serving up an index.html file if they have it available for a root path (like this one).
Rename public/index.html to public/setup_instructions.html and visit http://localhost:3000/ again.
You should get a routing error – this is because we didn’t follow the instructions about setting up a default route in config/routes.rb.
Note
You can refer back to the setup instructions by looking at http://localhost:3000/setup_instructions.html or just by looking at it in public/setup_instructions.html
Take a look at config/routes.rb and change
# map.root :controller => "welcome"
to point at the ArticlesController by changing it to
map.root :controller => "articles"
Refresh http://localhost:3000/ and you’ll see that we get an error about an “Unknown action”, and that no action responded to index.
Note
Make sure to watch the logs dumped out to the terminal where you started the rails server or by tailing log/development.log – it’s one of the best debugging tools you’ve got.
That’s easy to fix. Open up apps/controllers/articles_controller.rb.
Right now, it’s pretty bleak:
class ArticlesController < ApplicationController
end
The “index action” that Rails was complaining about being unknown just refers to there not being a public method called index on ArticlesController.
Fix that by adding one:
class ArticlesController < ApplicationController
© Copyright © 2009 Cody Fauser, James MacAulay, Edward Ocampo-Gooding, and John Guenin. Licenzija: Open Feedback Publishing System (OFPS)
