draft - IBM

arrogantpreviousInternet and Web Development

Feb 2, 2013 (4 years and 6 months ago)

265 views

Chapter 6.

Understanding Rails

(35 pages)


Understanding Rails: The big picture

@TODO

Directory Structure

When you use the “rails” command to create a rails application it automatically generates a basic directory structure. Rails
doesn't need to speci
fy anything, it knows where to find everything. Each directory has its own purpose. Let's take a look at
some of the most important directories and files.

@TODO: change it with a better picture and with the example application.


app

As rails is web
-
appli
cation framework that implements the MVC pattern (we will see it later),
app

directory holds all the files
related to this pattern. It splits the application in three layers: models, views and controllers.

In
models
directory are

all the models classes.
They should be named like
modelname.rb
and most of them will descend
from
ActiveRecord::Base
.

In
views

directory are all the template files for each view and they should be named like
resourcesname/actionname.html.erb
. There is a
layout
directory inside vi
ews directory, it holds the template files for layouts
to use with views. Layouts define header/footer method of wrapping views.

In
controllers

we'll find the the controller classes, they should be named like
controller name_controller.rb
. All controllers
should descend from
ApplicationController

which itself descends from
ActionController::Base
.

There is also a
helpers

directory which contains helper classes that should be named like
helpername_helper.rb
. Helpers will
help us assisting our views and wrapp
ing functionality from the views into methods.

config

It holds all the configuration files that rails need. It includes database configuration (
database.yml
), rails environments
configuration (
environment.rb
) and different configuration for each environme
nt (the default environments are
environments/development.rb
,
environments/production.rb

and
environments/test.rb
). There is also an important file that
defines the routing map (
routes.rb
).

db

It contains the database schema definition (
schema.rb
) and al
l the migrations for the schema (
migrate

folder)

log


There are the log files for each environment. If anything goes wrong you'll be able to inspect your application log files or
watch it in real time with "
tail
-
f
” in the
development.log
or
server.log

fil
es.

public


This directory is available for the web server. All the static contents are in this directory: stylesheets, javascript files,

images,
html files, etc. It's the DOCUMENT_ROOT or the web server.

test

It holds the units, the functional test and th
eir fixtures. Here you can create your test or modify all the tests that are created
when you use any of
script/generate

scripts.

vendor

In this directory are all the external libraries that the application depends on. If you freeze rails, those gems will
be copied
here under
vendor/rails
. This directory is in the load path.

Environments

In the application development process, it's useful to have different settings depending on the environment where you're
working on. For example when you're adding new fun
ctionality, you would like to see it in the development environment
previously to change it in production environment. Or if you are in production mode, it's not necessary to reload classes on
each request, cause they are not going to change periodically,
so it speeds up the application response. Or even when you
are running tests, you would like to do them against a special database for testing instead of production database.

For all those things, Rails allows you to setup different environments for each a
pplication. Rails creates three environments
by default: development, test and production. You can create new environments or modify the existent ones. To modify or add
settings to the environments you can do it in the config/environment.rb file. These cha
nges will affect to every environment.
But each environment has its own configuration file in config/environments/*.rb. Everything you write on them will overwrite
settings on environment.rb file.

Several processes read the environment.rb file like the web
rick server, the console, etc. At this point, even rails is loaded. So
you can specify the rails gems version on it with the option:

RAILS_GEM_VERSION = ‘2.3.2'.


Let's open the file config/environment.rb and review some of the settings inside of it.

All s
ettings except
RAILS_GEM_VERSION should be specified inside the Rails::Initializer.run block. An instance of
Rails::Configuration is passed to the block and assigned to the config variable. With it, you can change any attribute of
configuration. Some of th
em are:



frameworks
, you can remove some frameworks if you don't need them, just to enhance the performance, for example if
you don't use actionmailer and activeresource you can remove them by:

config.frameworks
-
= [ :active_record, :active_resource, :actio
n_mailer ]



gem
, you can specify which gems the application depends on, and if you don't have them you can install them running
the rake task “gems:install”. For example:

config.gem "hpricot", :version => '0.6', :source => "
http://code.whytheluckystiff.net
"

config.gem "sqlite3
-
ruby", :lib => "sqlite3"



log_level
, it is the log level to use for the Rails logger. In production mode the default is :info, in development mode it's
:debug.

config.log_level = :info

To see more settings, please visit the
http://api.rubyonrails.org/classes/Rails/Configuration.html

page.

MVC Architecture

Ruby on Rails is organized in the Model
-
View
-
Controller (
MVC) architecture. And for that reason, Rails divides the application
in three different layers: application’s data and functionality (Model), user interface (View), and control logic (Controller
), with
a minimal dependency among them.

With this, it's poss
ible to isolate the business logic from the user interface. So if you need to change the application
appearance or any of its business rules, it could be done easily without affecting each other.


Picture of MVC.


Models

are responsible of the application

business logic. They deal with the data and rules. In Rails a model represents a
database table, the relationships with other models, the validation rules and everything related with business. Rails uses
ActiveRecord to do it.

Views

are responsible for th
e user interface. In Rails they are files that contains HTML code together with embedded ruby
code (erb), the last one manipulates the data that is provided by the model.

Controllers

are the intermediary between views and model. A controller performs the r
equest action, then obtains the
necessary from the model and sends it to the action view.

@TODO: I would like to explain the entire workflow of a request with an example (of the application example).


IMAGE of Rails MVC (including routing)

Model

I will men
tion what is ActiveRecord and “Active Record” pattern.

Also the main features of AR (in some cases with samples of our application):



Associations (It will cover in the next chapter)



Validations (some basic validation helpers),



Finding records (.first, .al
l, .find with:conditions, order, limit)



Updating and deleting records.



Calculations(maximum, sum, count, average)



Dynamic finders


Generation

In order to get help from the console, I will show how to use “script/generate model” command (maybe I'll show
a
screenshot of the command output).

I'll explain how to create a simple model of our example application.

Naming Convention

I will show how ActiveRecord uses CoC including:



Automated mapping between classes and tables, attributes and columns.



Pluralization



Associations(primary keys and foreign keys)



Automated Record Timestamps


Views

I will explain the different types of templates, erb (.rhtml), builder (.rxml), JavaScriptGenerator (.rjs)

Working Embedded

I will start explaining how to mix ruby code and html

using <% %>, <%
-
%>, and <%= %> (some samples with
iterators or conditionals within html code).

Forms, Layouts and Helpers

Creating forms

I will explain how to create a form based in a model with form_for (explaining the difference between form_for
and fo
rm_tag). How it works when we submit it (params) and what happened if validations returns some errors.

I'll describe form inputs methods (text_field, label, text_area, check_box, submit_tag,)

Should I mention “fields_for” method? (for an additional model o
bject inside the form)

Sharing code with helpers

I'd like to highlight reasons to use helpers (duplication of code, share functionality, etc)

Also how to create a helper, how to use it in a view and share it to another controller's views.

Working with layo
uts

I'll explain the reasons to use layouts (header, footers) (DRY); how they are rendered, the yield method, how to
pass data to layouts (title example) and how to specify a different layout.

Controllers

Generation

In order to get help from the console, I

will show how to use “script/generate controller” command (maybe I'll
show a screenshot of the command output).

Also how to create a simple controller of our example application.

Linking the three

I'll explain why controllers are the core of web requests.


The relationship among the request, the controller's action and the template renderization (populating an
instance variable from model and passing it to the default template or a specific template).

I'll mention how to access to parameters, the respond_
to method, how to move to another action with redirect_to
and how to send messages with Flash object.

Should I talk about Sessions and Cookies?

Should I talk about filters?

RESTing with Rails

A simple description of REST.

I'll describe how to create RESTfu
l routes (and then run the rake routes task to see them)

I'll mention the seven actions of a restful controller (index, create, new, show, update, edit and destroy)

Should I talk about additional actions?

Should I talk about nested resources?

Static and D
ynamic Pages

I'm not sure if I understood this point.

Differences between static and dynamic pages?

How to create a static page in rails?


Exercises

@TODO

Summary

@TODO

Review Questions

@TODO


Generation

Naming Convention

Views

Working Embedded

Forms,
Layouts and Helpers

Creating forms

Sharing code with helpers

Working with layouts

Controllers

Generation

Linking the three

RESTing with Rails

Static and Dynamic Pages

Exercises

Summary

Review Questions