aboutsummaryrefslogtreecommitdiffstats
path: root/railties
diff options
context:
space:
mode:
authorMike Gunderloy <MikeG1@larkfarm.com>2008-09-08 14:57:09 -0500
committerMike Gunderloy <MikeG1@larkfarm.com>2008-09-08 14:57:09 -0500
commit14c42b5d12d619fdabba30fc4f2e6b9ac7c07418 (patch)
treedeef425d945bd86b697ccb750fb24a1529809f69 /railties
parent076347fc520e1bbd90a414288839cf1cb9e133b7 (diff)
parentf173ead371010af9332f7aa22b1f6cc309cac8a5 (diff)
downloadrails-14c42b5d12d619fdabba30fc4f2e6b9ac7c07418.tar.gz
rails-14c42b5d12d619fdabba30fc4f2e6b9ac7c07418.tar.bz2
rails-14c42b5d12d619fdabba30fc4f2e6b9ac7c07418.zip
Merge branch 'master' of git@github.com:lifo/docrails
Diffstat (limited to 'railties')
-rw-r--r--railties/doc/guides/debugging/debugging_rails_applications.txt157
-rw-r--r--railties/doc/guides/getting_started_with_rails/getting_started_with_rails.txt86
-rw-r--r--railties/doc/guides/migrations/scheming.txt36
3 files changed, 211 insertions, 68 deletions
diff --git a/railties/doc/guides/debugging/debugging_rails_applications.txt b/railties/doc/guides/debugging/debugging_rails_applications.txt
index 2c8477a1e4..b00a7f4328 100644
--- a/railties/doc/guides/debugging/debugging_rails_applications.txt
+++ b/railties/doc/guides/debugging/debugging_rails_applications.txt
@@ -1,22 +1,18 @@
Debugging Rails applications
============================
-You may have heard about debugging:
-
-_Debugging is a methodical process of finding and reducing the number of bugs, or defects, in a computer program or a piece of electronic hardware thus making it behave as expected._
-
-Many times your code may not behave as you expect, sometimes you will try to print in logs or console values to make a diagnostic of the problem.
-
-Unfortunately, you won't find always the answer you are looking for this way. In that case, you will need to know what's happening and adventure into Rails, in this journey the debugger will be your best companion.
-
-If you ever wanted to learn about Rails source code but you didn't know where to start, this may be the best way, just debug any request to your application and use this guide to learn how to move in the code you have written but also go deeper into Rails code.
+This guide covers how to debug Ruby on Rails applications. By referring to this guide, you will be able to:
+* Understand the purpose of debugging
+* Track down problems and issues in your application that your tests aren't identifying
+* Learn the different ways of debugging
+* Analyze the stack trace
== View helpers for debugging
=== debug
-*debug* will return a <pre>-tag that has object dumped by YAML. This creates a very readable way to inspect an object.
+*debug* will return a <pre>-tag that has object dumped by YAML. Generating readable output to inspect any object.
[source, html]
----------------------------------------------------------------------------
@@ -45,25 +41,9 @@ Title: Rails debugging guide
----------------------------------------------------------------------------
-=== local_assigns
-
-If you need to find out whether a certain local variable has been assigned a value in a particular render call, you need to use the following pattern:
-
-[source, html]
-----------------------------------------------------------------------------
- <% if local_assigns.has_key? :headline %>
- <p>Headline: <%= headline %></p>
- <% end %>
-----------------------------------------------------------------------------
-
-Using defined?(headline) will not work. This is an implementation restriction.
-
-[TIP]
-This is particularly handy inside partials, since you can know which variables have been defined and which haven't.
-
=== do it yourself
-Displaying an instance in yaml format, can be achieved this way:
+Displaying an instance variable, or any other object or method, in yaml format can be achieved this way:
[source, html]
----------------------------------------------------------------------------
@@ -74,9 +54,9 @@ Displaying an instance in yaml format, can be achieved this way:
</p>
----------------------------------------------------------------------------
-*to_yaml* converts the method to yaml format leaving it more readable and finally *simple_format* help us to render each line as in the console. This is how *debug* method does it's magic.
+*to_yaml* converts the method to yaml format leaving it more readable and finally *simple_format* help us to render each line as in the console. This is how *debug* method does its magic.
-As a result of this can see something like this in our view:
+As a result of this, you will have something like this in your view:
----------------------------------------------------------------------------
--- !ruby/object:Post
@@ -96,7 +76,7 @@ Another great method for displaying object values is *inspect*, especially when
[source, html]
----------------------------------------------------------------------------
-<%= [1, 1, 2, 3, 5].inspect %>
+<%= [1, 2, 3, 4, 5].inspect %>
<p>
<b>Title:</b>
<%=h @post.title %>
@@ -106,15 +86,125 @@ Another great method for displaying object values is *inspect*, especially when
Will be rendered as follows:
----------------------------------------------------------------------------
-[1, 2, 3]
+[1, 2, 3, 4, 5]
Title: Rails debugging guide
----------------------------------------------------------------------------
+== The logger
+
+=== What is it?
+
+Rails makes use of ruby’s standard *logger*, *Log4r*, or another logger that provides a similar interface can also be substituted if you wish.
+
+If you want to change the logger you can specify it in your *environment.rb* or any environment file.
+
+[source, ruby]
+----------------------------------------------------------------------------
+ActiveRecord::Base.logger = Logger.new(STDOUT)
+ActiveRecord::Base.logger = Log4r::Logger.new("Application Log")
+----------------------------------------------------------------------------
+
+Or in the __Initializer__ section, add _any_ of the following
+
+[source, ruby]
+----------------------------------------------------------------------------
+config.logger = Logger.new(STDOUT)
+config.logger = Log4r::Logger.new("Application Log")
+----------------------------------------------------------------------------
+
+[TIP]
+By default, each log is created under "__RAILS_ROOT/log/__" and the log file name is "__environment_name.log__".
+
+=== Log levels
+
+When something is logged it's printed into the corresponding log if the message log level is equal or higher than the configured log level. If you want to know the current log level just call *ActiveRecord::Base.logger.level* method.
+
+The available log levels are: *:debug*, *:info*, *:warn*, *:error*, *:fatal*, each level has a log level number from 0 up to 4 respectively. To change the default log level, use
+
+[source, ruby]
+----------------------------------------------------------------------------
+config.log_level = Logger::WARN # In any environment initializer, or
+ActiveRecord::Base.logger.level = 0 # at any time
+----------------------------------------------------------------------------
+
+This is useful when you want to log under development or staging, but you don't want to flood your production log with unnecessary information.
+
+[TIP]
+Rails default log level is *info* in production mode and *debug* in development and test mode.
+
+=== Sending messages
+
+To write in the current log use the *logger.(debug|info|warn|error|fatal)* method from within a controller, model or mailer:
+
+[source, ruby]
+----------------------------------------------------------------------------
+logger.debug "Person attributes hash: #{@person.attributes.inspect}"
+logger.info "Processing the request..."
+logger.fatal "Terminating application, raised unrecoverable error!!!"
+----------------------------------------------------------------------------
+
+A common example:
+
+[source, ruby]
+----------------------------------------------------------------------------
+class PostsController < ApplicationController
+ # ...
+
+ def create
+ @post = Post.new(params[:post])
+ logger.debug "New post: #{@post.attributes.inspect}"
+ logger.debug "Post should be valid: #{@post.valid?}"
+
+ if @post.save
+ flash[:notice] = 'Post was successfully created.'
+ logger.debug "The post was saved and now is the user is going to be redirected..."
+ redirect_to(@post)
+ else
+ render :action => "new"
+ end
+ end
+
+ # ...
+end
+----------------------------------------------------------------------------
+
+Will be logged like this:
+
+----------------------------------------------------------------------------
+Processing PostsController#create (for 127.0.0.1 at 2008-09-08 11:52:54) [POST]
+ Session ID: BAh7BzoMY3NyZl9pZCIlMDY5MWU1M2I1ZDRjODBlMzkyMWI1OTg2NWQyNzViZjYiCmZsYXNoSUM6J0FjdGlvbkNvbnRyb2xsZXI6OkZsYXNoOjpGbGFzaEhhc2h7AAY6CkB1c2VkewA=--b18cd92fba90eacf8137e5f6b3b06c4d724596a4
+ Parameters: {"commit"=>"Create", "post"=>{"title"=>"Debugging Rails", "body"=>"I'm learning how to print in logs!!!", "published"=>"0"}, "authenticity_token"=>"2059c1286e93402e389127b1153204e0d1e275dd", "action"=>"create", "controller"=>"posts"}
+New post: {"updated_at"=>nil, "title"=>"Debugging Rails", "body"=>"I'm learning how to print in logs!!!", "published"=>false, "created_at"=>nil}
+Post should be valid: true
+ Post Create (0.000443) INSERT INTO "posts" ("updated_at", "title", "body", "published", "created_at") VALUES('2008-09-08 14:52:54', 'Debugging Rails', 'I''m learning how to print in logs!!!', 'f', '2008-09-08 14:52:54')
+The post was saved and now is the user is going to be redirected...
+Redirected to #<Post:0x20af760>
+Completed in 0.01224 (81 reqs/sec) | DB: 0.00044 (3%) | 302 Found [http://localhost/posts]
+----------------------------------------------------------------------------
+
+Notice the logged lines, now you can search for any unexpected behavior in the output.
+
+By now you should know how to use the logs in any environment. Remember to take advantage of the log levels and use them wisely, mostly in production mode.
+
== Debugging with ruby-debug
+Many times your code may not behave as you expect, sometimes you will try to print in logs, console or view values to make a diagnostic of the problem.
+
+Unfortunately, you won't find always the answer you are looking for this way. In that case, you will need to know what's happening and adventure into Rails, in this journey the debugger will be your best companion.
+
+If you ever wanted to learn about Rails source code but you didn't know where to start, this may be the best way, just debug any request to your application and use this guide to learn how to move in the code you have written but also go deeper into Rails code.
+
=== Setup
+Ruby-debug comes as a gem so to install, just run:
+
+----------------------------------------------------------------------------
+$ sudo gem in ruby-debug
+----------------------------------------------------------------------------
+
+In case you want to download a particular version or get the source code, refer to link:http://rubyforge.org/projects/ruby-debug/[project's page on rubyforge].
+
Rails has built-in support for ruby-debug since April 28, 2007. Inside any Rails application you can invoke the debugger by calling the *debugger* method.
Let's take a look at an example:
@@ -504,5 +594,8 @@ set listsize 25
* link:http://www.sitepoint.com/article/debug-rails-app-ruby-debug/[Article: Debugging a Rails application with ruby-debug]
* link:http://brian.maybeyoureinsane.net/blog/2007/05/07/ruby-debug-basics-screencast/[ruby-debug Basics screencast]
* link:http://railscasts.com/episodes/54-debugging-with-ruby-debug[Ryan Bate's ruby-debug screencast]
+* link:http://railscasts.com/episodes/24-the-stack-trace[Ryan Bate's stack trace screencast]
+* link:http://railscasts.com/episodes/56-the-logger[Ryan Bate's logger screencast]
* link:http://bashdb.sourceforge.net/ruby-debug.html[Debugging with ruby-debug]
-* link:http://cheat.errtheblog.com/s/rdebug/[ruby-debug cheat sheet] \ No newline at end of file
+* link:http://cheat.errtheblog.com/s/rdebug/[ruby-debug cheat sheet]
+* link:http://wiki.rubyonrails.org/rails/pages/HowtoConfigureLogging[Ruby on Rails Wiki: How to Configure Logging] \ No newline at end of file
diff --git a/railties/doc/guides/getting_started_with_rails/getting_started_with_rails.txt b/railties/doc/guides/getting_started_with_rails/getting_started_with_rails.txt
index b8557dd52a..a798bfa218 100644
--- a/railties/doc/guides/getting_started_with_rails/getting_started_with_rails.txt
+++ b/railties/doc/guides/getting_started_with_rails/getting_started_with_rails.txt
@@ -16,18 +16,17 @@ This guide is designed for beginners who want to get started with a Rails applic
Rails is a web development framework written in the Ruby language. It is designed to make programming web applications easier by making several assumptions about what every developer needs to get started. It allows you to write less code while accomplishing more than other languages and frameworks.
== Installing Rails
------------------
-gem install rails
------------------
+
+`gem install rails`
== Create a new Rails project
We're going to create a Rails project called "blog", which is the project that we will build off of for this guide.
From your terminal, type:
-----------
-rails blog
-----------
+
+`rails blog`
+
This will create the a folder in your working directory called "blog". Open up that folder and have a look. For the majority of this tutorial, we will live in the app/ folder, but here's a basic rundown on the function of each folder in a Rails app:
[grid="all"]
@@ -76,18 +75,18 @@ production:
timeout: 5000
--------------------------------------------------------------------
If you're not running OS X 10.5 or greater, you'll need to install the SQLite gem. Similar to installing Rails you just need to run:
-------------------------
-gem install sqlite3-ruby
-------------------------
+
+`gem install sqlite3-ruby`
+
Because we're using SQLite, there's really nothing else you need to do to setup your database!
=== Configure MySQL Database
.MySQL Tip
*******************************
If you want to skip directly to using MySQL on your development machine, type the following will get you setup with a MySQL configuration file that assumes MySQL is running locally and that the root password is blank:
------------------
-rails blog -d mysql
------------------
+
+`rails blog -d mysql`
+
You'll need to make sure you have MySQL up and running on your system with the correct permissions. MySQL installation and configuration is outside the scope of this document.
*******************************
If you choose to use MySQL, your +config/database.yml+ will look a little different:
@@ -136,19 +135,17 @@ production:
socket: /tmp/mysql.sock
----------------------------------------------------------------------
-== Starting the webserver
-Rails comes bundled with the lightweight Webrick web server, which (like SQLite) works great in development, but is not designed for a production environment.
+== Starting the web server
+Rails comes bundled with the lightweight Webrick web server, which (like SQLite) works great in development, but is not designed for a production environment. If you install Mongrel with `gem install mongrel`, Rails will use the Mongrel web server as the default instead (recommended).
*******************
If you're interested in alternative web servers for development and/or production, check out mod_rails (a.k.a Passenger)
*******************
Rails lets you run in development, test, and production environments (you can also add an unlimited number of additional environments if necessary). In this guide, we're going to work with the development environment only, which is the default when starting the server. From the root of your application folder, simply type the following to startup the web server:
----------------
-./script/server
----------------
-This will start a process that allows you to connect to your application via a web browser on port 3000. Open up a browser to:
-----------------------
-http://localhost:3000/
-----------------------
+
+`./script/server`
+
+This will start a process that allows you to connect to your application via a web browser on port 3000. Open up a browser to +http://localhost:3000/+
+
You should see the "Welcome Aboard" default Rails screen, and can click on the "About your application's environment" link to see a brief summary of your current configuration. If you've gotten this far, you're riding rails! Let's dive into the code!
== Models, Views, and Controllers
@@ -158,20 +155,21 @@ Rails uses Model, View, Controller (MVC) architecture because it isolates busine
The model represents the information (data) of the application and the rules to manipulate that data. In the case of Rails, models are primarily used for managing the rules of interaction with a corresponding database table. Assume that for every table in your database, you will have a corresponding model (not necessarily the other way around, but that's beyond the scope of this guide).
Models in Rails use a singular name, and their corresponding database tables use a plural name. In the case of our "Blog" application, we're going to need a table for our blog posts. Because we're generating a model, we want to use the singular name:
-----------------------------
-./script/generate model Post
-----------------------------
+
+`./script/generate model Post`
+
You'll see that this generates several files, we're going to focus on two. First, let's take a look at +app/models/post.rb+
-------------------------------
class Post < ActiveRecord::Base
end
-------------------------------
-This is what each model you create will look like by default. Here Rails is making the assumption that your Post model will be tied to a database, because it is telling the Post class to inherit from the ActiveRecord::Base class, which is where all the database magic happens. Let's leave the model alone for now and move onto migrations.
+This is what each model you create will look like by default. Here Rails is making the assumption that your Post model will be tied to a database, because it is telling the Post class to descend from the ActiveRecord::Base class, which is where all the database magic happens. Let's leave the model alone for now and move onto migrations.
==== Migrations
Database migrations make it simple to add/remove/modify tables, columns, and indexes while allowing you to roll back or forward between states with ease.
Have a look at +db/migrate/2008XXXXXXXXXX_create_posts.rb+ (Yours will have numbers specific to the time that the file was generated), which was generated when creating our Post model:
+
-------------------------------------------
class CreatePosts < ActiveRecord::Migration
def self.up
@@ -186,9 +184,11 @@ class CreatePosts < ActiveRecord::Migration
end
end
-------------------------------------------
+
By default, Rails creates a database migration that will create the table for "posts" (plural name of model). The +create_table+ method takes a ruby block, and by default you'll see +t.timestamps+ in there, which automatically creates and automatically handles +created_at+ and +updated_at+ datetime columns. The +self.up+ section handles progression of the database, whereas the +self.down+ handles regression (or rollback) of the migration.
Let's add some more columns to our migration that suit our post table. We'll create a +name+ column for the person who wrote the post, a +title+ column for the title of the post, and a +content+ column for the actual post content.
+
-------------------------------------------
class CreatePosts < ActiveRecord::Migration
def self.up
@@ -206,9 +206,9 @@ class CreatePosts < ActiveRecord::Migration
end
-------------------------------------------
Now that we have our migration just right, we can run the migration (the +self.up+ portion) by returning to the terminal and running:
----------------
-rake db:migrate
----------------
+
+`rake db:migrate`
+
This command will always run any migrations that have not yet been run.
.Singular and Plural Inflections
@@ -223,21 +223,43 @@ The controller communicates input from the user (the view) to the model.
The REST idea will likely take some time to wrap your brain around if you're new to the concept. But know the following:
* It is best to keep your controllers RESTful at all times if possible
-* Resources must be defined in +config/routes.rb+ in order for the RESTful architecture to work properly
+* Resources must be defined in +config/routes.rb+ in order for the RESTful architecture to work properly, so let's add that now:
--------------------
map.resources :posts
--------------------
-* The seven actions that are automatically part of the RESTful design in Rails are +index+, +show+, +create+, +edit+, +update+, and +destroy+
+* The seven actions that are automatically part of the RESTful design in Rails are +index+, +show+, +new+, +create+, +edit+, +update+, and +destroy+.
-=== The View
-The view is where you put all the code that gets seen by the user: divs, tables, text, checkboxes, etc. Think of the view as the home of your HTML. If done correctly, there should be no business logic in the view.
+Let's generate a controller:
+
+`./script/generate controller Posts`
+
+Open up the controller that it generates in +app/controllers/posts_controller.rb+. It should look like:
+---------------------------------------------
+class PostsController < ApplicationController
+end
+---------------------------------------------
+Because of the +map.resources :posts+ line in your +config/routes.rb+ file, this controller is ready to take on all seven actions listed above. But we're going to need some logic in this controller in order to interact with the model, and we're going to need to generate our view files so the user can interact with your application from their browser.
+
+We're going to use the scaffold generator to create all the files and basic logic to make this work, now that you know how to generate models and controllers manually.
+
+To do that, let's completely start over. Back out of your Rails project folder, and *remove it completely* (`rm -rf blog`).
+Create the project again and enter the directory by running the commands:
+
+`rails blog`
+`cd blog`
+=== Rails Scaffold
+Whenever you are dealing with a resource and you know you'll need a way to manage that resource in your application, you can start by generating a scaffold. The reason that this guide did not start with generating the scaffold is because it is not all that useful once you For our blog, we want our "Post" resource, so let's generate that now:
+`./script/generate scaffold Post name:string title:string content:text`
+=== The View
+The view is where you put all the code that gets seen by the user: divs, tables, text, checkboxes, etc. Think of the view as the home of your HTML. If done correctly, there should be no business logic in the view.
+
diff --git a/railties/doc/guides/migrations/scheming.txt b/railties/doc/guides/migrations/scheming.txt
index 21cfe0d927..5a2e04cf8c 100644
--- a/railties/doc/guides/migrations/scheming.txt
+++ b/railties/doc/guides/migrations/scheming.txt
@@ -1,16 +1,44 @@
== Schema dumping and you ==
-Migrations, mighty as they may be, are not the final word in what an application's schema is. That role falls to either `schema.rb` or an sql file.
-There is no need (and it is error prone) to deploy a new instance of an app by replaying the entire history of that application. It is much simpler to just load into the database a description of the current schema.
+=== What are schema files for? ===
+Migrations, mighty as they may be, are not the authoritative source for your database schema. That role falls to either `schema.rb` or an sql file which Active Record generates by examining the database. They are not designed to be edited, they just represent the current state of the database.
+
+There is no need (and it is error prone) to deploy a new instance of an app by replaying the entire migration history. It is much simpler and faster to just load into the database a description of the current schema.
For example, this is how the test database is created: the current development database is dumped (either to `schema.rb` or `development.sql`) and then loaded.
+=== Types of schema dumps ===
There are two ways to dump the schema. This is set in `config/environment.rb` by the `config.active_record.schema_format` setting, which may be either `:sql` or `:ruby`.
-If `:ruby` is selected then the schema is stored in `db/schema.rb`. If you look at this file you'll find that it looks an awful lot like one very big migration. In many ways this is exactly what it is. This file is created by inspecting the database and expressing its structure using `create_table`, `add_index` and so on. Because this is database independent it could be loaded into any database that Active Record supports. This could be very useful if you were to distribute an application that is able to run against multiple databases.
+If `:ruby` is selected then the schema is stored in `db/schema.rb`. If you look at this file you'll find that it looks an awful lot like one very big migration:
+
+[source, ruby]
+--------------------------------------
+ActiveRecord::Schema.define(:version => 20080906171750) do
+ create_table "authors", :force => true do |t|
+ t.string "name"
+ t.datetime "created_at"
+ t.datetime "updated_at"
+ end
+
+ create_table "products", :force => true do |t|
+ t.string "name"
+ t.text "description"
+ t.datetime "created_at"
+ t.datetime "updated_at"
+ t.string "part_number"
+ end
+end
+--------------------------------------
+
+In many ways this is exactly what it is. This file is created by inspecting the database and expressing its structure using `create_table`, `add_index` and so on. Because this is database independent it could be loaded into any database that Active Record supports. This could be very useful if you were to distribute an application that is able to run against multiple databases.
There is however a trade-off: `schema.rb` cannot express database specific items such as foreign key constraints. While in a migration you can execute custom sql statements, the schema dumper cannot reconstitute those statements from the database. If you are using features like this then you should set the schema format to `:sql`.
Instead of using Active Record 's schema dumper the database's structure will dumped using a tool specific to that database (via the `db:structure:dump` rake task) into `db/#\{RAILS_ENV\}_structure.sql`. For example for postgresql the `pg_dump` utility is used and for mysql this file will contain the output of SHOW CREATE TABLE for the various tables. Loading this schema is simply a question of executing the sql statements contained inside.
-By definition this will be a perfect copy of the database's structure but this will usually prevent loading the schema into a database other than the one used to create it. \ No newline at end of file
+By definition this will be a perfect copy of the database's structure but this will usually prevent loading the schema into a database other than the one used to create it.
+
+=== Schema dumps and source control ===
+
+Because they are the authoritative source for your database schema, it is strongly recommended that you check them into source control. \ No newline at end of file