From eb2d555f5c2e504f9de73dd083f148336f5ffa19 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?David=20Rodr=C3=ADguez=20de=20Dios?= Date: Tue, 8 Apr 2014 20:59:28 +0200 Subject: Update debugging guide to use byebug --- guides/source/debugging_rails_applications.md | 423 +++++++++++++++----------- 1 file changed, 246 insertions(+), 177 deletions(-) (limited to 'guides') diff --git a/guides/source/debugging_rails_applications.md b/guides/source/debugging_rails_applications.md index 0e10d1b697..2357399900 100644 --- a/guides/source/debugging_rails_applications.md +++ b/guides/source/debugging_rails_applications.md @@ -240,130 +240,109 @@ The contents of the block, and therefore the string interpolation, is only evaluated if debug is enabled. This performance savings is only really noticeable with large amounts of logging, but it's a good practice to employ. -Debugging with the `debugger` gem +Debugging with the `byebug` gem --------------------------------- -When your code is behaving in unexpected ways, you can try printing to logs or the console to diagnose the problem. Unfortunately, there are times when this sort of error tracking is not effective in finding the root cause of a problem. When you actually need to journey into your running source code, the debugger is your best companion. +When your code is behaving in unexpected ways, you can try printing to logs or +the console to diagnose the problem. Unfortunately, there are times when this +sort of error tracking is not effective in finding the root cause of a problem. +When you actually need to journey into your running source code, the debugger +is your best companion. -The debugger can also help you if you want to learn about the Rails source code but don't know where to start. Just debug any request to your application and use this guide to learn how to move from the code you have written deeper into Rails code. +The debugger can also help you if you want to learn about the Rails source code +but don't know where to start. Just debug any request to your application and +use this guide to learn how to move from the code you have written deeper into +Rails code. ### Setup -You can use the `debugger` gem to set breakpoints and step through live code in Rails. To install it, just run: +You can use the `byebug` gem to set breakpoints and step through live code in +Rails. To install it, just run: ```bash -$ gem install debugger +$ gem install byebug ``` -Rails has had built-in support for debugging since Rails 2.0. Inside any Rails application you can invoke the debugger by calling the `debugger` method. +Inside any Rails application you can then invoke the debugger by calling the +`byebug` method. Here's an example: ```ruby class PeopleController < ApplicationController def new - debugger + byebug @person = Person.new end end ``` -If you see this message in the console or logs: - -``` -***** Debugger requested, but was not available: Start server with --debugger to enable ***** -``` - -Make sure you have started your web server with the option `--debugger`: - -```bash -$ rails server --debugger -=> Booting WEBrick -=> Rails 4.0.0 application starting on http://0.0.0.0:3000 -=> Debugger enabled -... -``` - -TIP: In development mode, you can dynamically `require \'debugger\'` instead of restarting the server, even if it was started without `--debugger`. - ### The Shell -As soon as your application calls the `debugger` method, the debugger will be started in a debugger shell inside the terminal window where you launched your application server, and you will be placed at the debugger's prompt `(rdb:n)`. The _n_ is the thread number. The prompt will also show you the next line of code that is waiting to run. - -If you got there by a browser request, the browser tab containing the request will be hung until the debugger has finished and the trace has finished processing the entire request. - -For example: - -```bash -@posts = Post.all -(rdb:7) -``` - -Now it's time to explore and dig into your application. A good place to start is by asking the debugger for help. Type: `help` - -``` -(rdb:7) help -ruby-debug help v0.10.2 -Type 'help ' for help on a specific command - -Available commands: -backtrace delete enable help next quit show trace -break disable eval info p reload source undisplay -catch display exit irb pp restart step up -condition down finish list ps save thread var -continue edit frame method putl set tmate where -``` - -TIP: To view the help menu for any command use `help ` at the debugger prompt. For example: _`help var`_ - -The next command to learn is one of the most useful: `list`. You can abbreviate any debugging command by supplying just enough letters to distinguish them from other commands, so you can also use `l` for the `list` command. - -This command shows you where you are in the code by printing 10 lines centered around the current line; the current line in this particular case is line 6 and is marked by `=>`. +As soon as your application calls the `byebug` method, the debugger will be +started in a debugger shell inside the terminal window where you launched your +application server, and you will be placed at the debugger's prompt `(byebug)`. +Before the prompt, the code around the line that is about to be run will be +shown and the current line is marked by '=>'. Like this: ``` -(rdb:7) list [1, 10] in /PathTo/project/app/controllers/posts_controller.rb 1 class PostsController < ApplicationController 2 # GET /posts 3 # GET /posts.json 4 def index - 5 debugger + 5 byebug => 6 @posts = Post.all 7 8 respond_to do |format| 9 format.html # index.html.erb 10 format.json { render json: @posts } +(byebug) ``` -If you repeat the `list` command, this time using just `l`, the next ten lines of the file will be printed out. +If you got there by a browser request, the browser tab containing the request +will be hung until the debugger has finished and the trace has finished +processing the entire request. +For example: + +```bash +@posts = Post.all +(rdb:7) ``` -(rdb:7) l -[11, 20] in /PathTo/project/app/controllers/posts_controller.rb - 11 end - 12 end - 13 - 14 # GET /posts/1 - 15 # GET /posts/1.json - 16 def show - 17 @post = Post.find(params[:id]) - 18 - 19 respond_to do |format| - 20 format.html # show.html.erb + +Now it's time to explore and dig into your application. A good place to start is +by asking the debugger for help. Type: `help` + ``` +(byebug) help +byebug 2.6.0 -And so on until the end of the current file. When the end of file is reached, the `list` command will start again from the beginning of the file and continue again up to the end, treating the file as a circular buffer. +Type 'help ' for help on a specific command -On the other hand, to see the previous ten lines you should type `list-` (or `l-`) +Available commands: +backtrace delete enable help list pry next restart source up +break disable eval info method ps save step var +catch display exit interrupt next putl set thread +condition down finish irb p quit show trace +continue edit frame kill pp reload skip undisplay +``` + +TIP: To view the help menu for any command use `help ` at the +debugger prompt. For example: _`help list`_. You can abbreviate any debugging +command by supplying just enough letters to distinguish them from other +commands, so you can also use `l` for the `list` command, for example. + +To see the previous ten lines you should type `list-` (or `l-`) ``` -(rdb:7) l- +(byebug) l- [1, 10] in /PathTo/project/app/controllers/posts_controller.rb 1 class PostsController < ApplicationController 2 # GET /posts 3 # GET /posts.json 4 def index - 5 debugger + 5 byebug 6 @posts = Post.all 7 8 respond_to do |format| @@ -371,17 +350,18 @@ On the other hand, to see the previous ten lines you should type `list-` (or `l- 10 format.json { render json: @posts } ``` -This way you can move inside the file, being able to see the code above and over the line you added the `debugger`. -Finally, to see where you are in the code again you can type `list=` +This way you can move inside the file, being able to see the code above and over +the line you added the `byebug` call. Finally, to see where you are in the code +again you can type `list=` ``` -(rdb:7) list= +(byebug) list= [1, 10] in /PathTo/project/app/controllers/posts_controller.rb 1 class PostsController < ApplicationController 2 # GET /posts 3 # GET /posts.json 4 def index - 5 debugger + 5 byebug => 6 @posts = Post.all 7 8 respond_to do |format| @@ -391,14 +371,22 @@ Finally, to see where you are in the code again you can type `list=` ### The Context -When you start debugging your application, you will be placed in different contexts as you go through the different parts of the stack. +When you start debugging your application, you will be placed in different +contexts as you go through the different parts of the stack. -The debugger creates a context when a stopping point or an event is reached. The context has information about the suspended program which enables a debugger to inspect the frame stack, evaluate variables from the perspective of the debugged program, and contains information about the place where the debugged program is stopped. +The debugger creates a context when a stopping point or an event is reached. The +context has information about the suspended program which enables the debugger +to inspect the frame stack, evaluate variables from the perspective of the +debugged program, and contains information about the place where the debugged +program is stopped. -At any time you can call the `backtrace` command (or its alias `where`) to print the backtrace of the application. This can be very helpful to know how you got where you are. If you ever wondered about how you got somewhere in your code, then `backtrace` will supply the answer. +At any time you can call the `backtrace` command (or its alias `where`) to print +the backtrace of the application. This can be very helpful to know how you got +where you are. If you ever wondered about how you got somewhere in your code, +then `backtrace` will supply the answer. ``` -(rdb:5) where +(byebug) where #0 PostsController.index at line /PathTo/project/app/controllers/posts_controller.rb:6 #1 Kernel.send @@ -410,46 +398,64 @@ At any time you can call the `backtrace` command (or its alias `where`) to print ... ``` -You move anywhere you want in this trace (thus changing the context) by using the `frame _n_` command, where _n_ is the specified frame number. +You move anywhere you want in this trace (thus changing the context) by using +the `frame _n_` command, where _n_ is the specified frame number. ``` -(rdb:5) frame 2 +(byebug) frame 2 #2 ActionController::Base.perform_action_without_filters at line /PathTo/project/vendor/rails/actionpack/lib/action_controller/base.rb:1175 ``` -The available variables are the same as if you were running the code line by line. After all, that's what debugging is. +The available variables are the same as if you were running the code line by +line. After all, that's what debugging is. -Moving up and down the stack frame: You can use `up [n]` (`u` for abbreviated) and `down [n]` commands in order to change the context _n_ frames up or down the stack respectively. _n_ defaults to one. Up in this case is towards higher-numbered stack frames, and down is towards lower-numbered stack frames. +Moving up and down the stack frame: You can use `up [n]` (`u` for abbreviated) +and `down [n]` commands in order to change the context _n_ frames up or down the +stack respectively. _n_ defaults to one. Up in this case is towards +higher-numbered stack frames, and down is towards lower-numbered stack frames. ### Threads -The debugger can list, stop, resume and switch between running threads by using the command `thread` (or the abbreviated `th`). This command has a handful of options: +The debugger can list, stop, resume and switch between running threads by using +the command `thread` (or the abbreviated `th`). This command has a handful of +options: * `thread` shows the current thread. -* `thread list` is used to list all threads and their statuses. The plus + character and the number indicates the current thread of execution. +* `thread list` is used to list all threads and their statuses. The plus + +character and the number indicates the current thread of execution. * `thread stop _n_` stop thread _n_. * `thread resume _n_` resumes thread _n_. * `thread switch _n_` switches the current thread context to _n_. -This command is very helpful, among other occasions, when you are debugging concurrent threads and need to verify that there are no race conditions in your code. +This command is very helpful, among other occasions, when you are debugging +concurrent threads and need to verify that there are no race conditions in your +code. ### Inspecting Variables -Any expression can be evaluated in the current context. To evaluate an expression, just type it! +Any expression can be evaluated in the current context. To evaluate an +expression, just type it! -This example shows how you can print the instance_variables defined within the current context: +This example shows how you can print the instance_variables defined within the +current context: ``` @posts = Post.all -(rdb:11) instance_variables -["@_response", "@action_name", "@url", "@_session", "@_cookies", "@performed_render", "@_flash", "@template", "@_params", "@before_filter_chain_aborted", "@request_origin", "@_headers", "@performed_redirect", "@_request"] +(byebug) instance_variables +["@_response", "@action_name", "@url", "@_session", "@_cookies", + "@performed_render", "@_flash", "@template", "@_params", + "@before_filter_chain_aborted", "@request_origin", "@_headers", + "@performed_redirect", "@_request"] ``` -As you may have figured out, all of the variables that you can access from a controller are displayed. This list is dynamically updated as you execute code. For example, run the next line using `next` (you'll learn more about this command later in this guide). +As you may have figured out, all of the variables that you can access from a +controller are displayed. This list is dynamically updated as you execute code. +For example, run the next line using `next` (you'll learn more about this +command later in this guide). ``` -(rdb:11) next +(byebug) next Processing PostsController#index (for 127.0.0.1 at 2008-09-04 19:51:34) [GET] Session ID: BAh7BiIKZmxhc2hJQzonQWN0aW9uQ29udHJvbGxlcjo6Rmxhc2g6OkZsYXNoSGFzaHsABjoKQHVzZWR7AA==--b16e91b992453a8cc201694d660147bba8b0fd0e Parameters: {"action"=>"index", "controller"=>"posts"} @@ -460,64 +466,80 @@ respond_to do |format| And then ask again for the instance_variables: ``` -(rdb:11) instance_variables.include? "@posts" +(byebug) instance_variables.include? "@posts" true ``` -Now `@posts` is included in the instance variables, because the line defining it was executed. +Now `@posts` is included in the instance variables, because the line defining it +was executed. -TIP: You can also step into **irb** mode with the command `irb` (of course!). This way an irb session will be started within the context you invoked it. But be warned: this is an experimental feature. +TIP: You can also step into **irb** mode with the command `irb` (of course!). +This way an irb session will be started within the context you invoked it. But +be warned: this is an experimental feature. The `var` method is the most convenient way to show variables and their values: ``` var -(rdb:1) v[ar] const show constants of object -(rdb:1) v[ar] g[lobal] show global variables -(rdb:1) v[ar] i[nstance] show instance variables of object -(rdb:1) v[ar] l[ocal] show local variables +(byebug) v[ar] const show constants of object +(byebug) v[ar] g[lobal] show global variables +(byebug) v[ar] i[nstance] show instance variables of object +(byebug) v[ar] l[ocal] show local variables ``` -This is a great way to inspect the values of the current context variables. For example: +This is a great way to inspect the values of the current context variables. For +example: ``` -(rdb:9) var local +(byebug) var local __dbg_verbose_save => false ``` You can also inspect for an object method this way: ``` -(rdb:9) var instance Post.new +(byebug) var instance Post.new @attributes = {"updated_at"=>nil, "body"=>nil, "title"=>nil, "published"=>nil, "created_at"... @attributes_cache = {} @new_record = true ``` -TIP: The commands `p` (print) and `pp` (pretty print) can be used to evaluate Ruby expressions and display the value of variables to the console. +TIP: The commands `p` (print) and `pp` (pretty print) can be used to evaluate +Ruby expressions and display the value of variables to the console. -You can use also `display` to start watching variables. This is a good way of tracking the values of a variable while the execution goes on. +You can use also `display` to start watching variables. This is a good way of +tracking the values of a variable while the execution goes on. ``` -(rdb:1) display @recent_comments +(byebug) display @recent_comments 1: @recent_comments = ``` -The variables inside the displaying list will be printed with their values after you move in the stack. To stop displaying a variable use `undisplay _n_` where _n_ is the variable number (1 in the last example). +The variables inside the displaying list will be printed with their values after +you move in the stack. To stop displaying a variable use `undisplay _n_` where +_n_ is the variable number (1 in the last example). ### Step by Step -Now you should know where you are in the running trace and be able to print the available variables. But lets continue and move on with the application execution. +Now you should know where you are in the running trace and be able to print the +available variables. But lets continue and move on with the application +execution. -Use `step` (abbreviated `s`) to continue running your program until the next logical stopping point and return control to the debugger. +Use `step` (abbreviated `s`) to continue running your program until the next +logical stopping point and return control to the debugger. -TIP: You can also use `step+ n` and `step- n` to move forward or backward `n` steps respectively. +TIP: You can also use `step+ n` and `step- n` to move forward or backward `n` +steps respectively. -You may also use `next` which is similar to step, but function or method calls that appear within the line of code are executed without stopping. As with step, you may use plus sign to move _n_ steps. +You may also use `next` which is similar to step, but function or method calls +that appear within the line of code are executed without stopping. As with +`step`, you may use plus sign to move _n_ steps. -The difference between `next` and `step` is that `step` stops at the next line of code executed, doing just a single step, while `next` moves to the next line without descending inside methods. +The difference between `next` and `step` is that `step` stops at the next line +of code executed, doing just a single step, while `next` moves to the next line +without descending inside methods. -For example, consider this block of code with an included `debugger` statement: +For example, consider this block of code with an included `byebug` statement: ```ruby class Author < ActiveRecord::Base @@ -525,53 +547,46 @@ class Author < ActiveRecord::Base has_many :comments def find_recent_comments(limit = 10) - debugger + byebug @recent_comments ||= comments.where("created_at > ?", 1.week.ago).limit(limit) end end ``` -TIP: You can use the debugger while using `rails console`. Just remember to `require "debugger"` before calling the `debugger` method. - ``` $ rails console Loading development environment (Rails 4.0.0) ->> require "debugger" -=> [] >> author = Author.first => # >> author.find_recent_comments /PathTo/project/app/models/author.rb:11 ) -``` - -With the code stopped, take a look around: - -``` -(rdb:1) list [2, 9] in /PathTo/project/app/models/author.rb 2 has_one :editorial 3 has_many :comments 4 5 def find_recent_comments(limit = 10) - 6 debugger + 6 byebug => 7 @recent_comments ||= comments.where("created_at > ?", 1.week.ago).limit(limit) 8 end 9 end +(byebug) ``` -You are at the end of the line, but... was this line executed? You can inspect the instance variables. +You are at the end of the line, but... was this line executed? You can inspect +the instance variables. ``` -(rdb:1) var instance +(byebug) var instance @attributes = {"updated_at"=>"2008-07-31 12:46:10", "id"=>"1", "first_name"=>"Bob", "las... @attributes_cache = {} ``` -`@recent_comments` hasn't been defined yet, so it's clear that this line hasn't been executed yet. Use the `next` command to move on in the code: +`@recent_comments` hasn't been defined yet, so it's clear that this line hasn't +been executed yet. Use the `next` command to move on in the code: ``` -(rdb:1) next +(byebug) next /PathTo/project/app/models/author.rb:12 @recent_comments (rdb:1) var instance @@ -581,89 +596,119 @@ You are at the end of the line, but... was this line executed? You can inspect t @recent_comments = [] ``` -Now you can see that the `@comments` relationship was loaded and @recent_comments defined because the line was executed. +Now you can see that the `@comments` relationship was loaded and +`@recent_comments` defined because the line was executed. -If you want to go deeper into the stack trace you can move single `steps`, through your calling methods and into Rails code. This is one of the best ways to find bugs in your code, or perhaps in Ruby or Rails. +If you want to go deeper into the stack trace you can move single steps +through your calling methods and into Rails code. This is one of the best ways +to find bugs in your code, or perhaps in Ruby or Rails. ### Breakpoints -A breakpoint makes your application stop whenever a certain point in the program is reached. The debugger shell is invoked in that line. +A breakpoint makes your application stop whenever a certain point in the program +is reached. The debugger shell is invoked in that line. -You can add breakpoints dynamically with the command `break` (or just `b`). There are 3 possible ways of adding breakpoints manually: +You can add breakpoints dynamically with the command `break` (or just `b`). +There are 3 possible ways of adding breakpoints manually: * `break line`: set breakpoint in the _line_ in the current source file. -* `break file:line [if expression]`: set breakpoint in the _line_ number inside the _file_. If an _expression_ is given it must evaluated to _true_ to fire up the debugger. -* `break class(.|\#)method [if expression]`: set breakpoint in _method_ (. and \# for class and instance method respectively) defined in _class_. The _expression_ works the same way as with file:line. +* `break file:line [if expression]`: set breakpoint in the _line_ number inside +the _file_. If an _expression_ is given it must evaluated to _true_ to fire up +the debugger. +* `break class(.|\#)method [if expression]`: set breakpoint in _method_ (. and +\# for class and instance method respectively) defined in _class_. The +_expression_ works the same way as with file:line. + ``` -(rdb:5) break 10 +(byebug:5) break 10 Breakpoint 1 file /PathTo/project/vendor/rails/actionpack/lib/action_controller/filters.rb, line 10 ``` -Use `info breakpoints _n_` or `info break _n_` to list breakpoints. If you supply a number, it lists that breakpoint. Otherwise it lists all breakpoints. +Use `info breakpoints _n_` or `info break _n_` to list breakpoints. If you +supply a number, it lists that breakpoint. Otherwise it lists all breakpoints. ``` -(rdb:5) info breakpoints +(byebug:5) info breakpoints Num Enb What 1 y at filters.rb:10 ``` -To delete breakpoints: use the command `delete _n_` to remove the breakpoint number _n_. If no number is specified, it deletes all breakpoints that are currently active.. +To delete breakpoints: use the command `delete _n_` to remove the breakpoint +number _n_. If no number is specified, it deletes all breakpoints that are +currently active. ``` -(rdb:5) delete 1 -(rdb:5) info breakpoints +(byebug:5) delete 1 +(byebug:5) info breakpoints No breakpoints. ``` You can also enable or disable breakpoints: -* `enable breakpoints`: allow a list _breakpoints_ or all of them if no list is specified, to stop your program. This is the default state when you create a breakpoint. +* `enable breakpoints`: allow a list _breakpoints_ or all of them if no list is +specified, to stop your program. This is the default state when you create a +breakpoint. * `disable breakpoints`: the _breakpoints_ will have no effect on your program. ### Catching Exceptions -The command `catch exception-name` (or just `cat exception-name`) can be used to intercept an exception of type _exception-name_ when there would otherwise be is no handler for it. +The command `catch exception-name` (or just `cat exception-name`) can be used to +intercept an exception of type _exception-name_ when there would otherwise be no +handler for it. To list all active catchpoints use `catch`. ### Resuming Execution -There are two ways to resume execution of an application that is stopped in the debugger: - -* `continue` [line-specification] \(or `c`): resume program execution, at the address where your script last stopped; any breakpoints set at that address are bypassed. The optional argument line-specification allows you to specify a line number to set a one-time breakpoint which is deleted when that breakpoint is reached. -* `finish` [frame-number] \(or `fin`): execute until the selected stack frame returns. If no frame number is given, the application will run until the currently selected frame returns. The currently selected frame starts out the most-recent frame or 0 if no frame positioning (e.g up, down or frame) has been performed. If a frame number is given it will run until the specified frame returns. +There are two ways to resume execution of an application that is stopped in the +debugger: + +* `continue` [line-specification] \(or `c`): resume program execution, at the +address where your script last stopped; any breakpoints set at that address are +bypassed. The optional argument line-specification allows you to specify a line +number to set a one-time breakpoint which is deleted when that breakpoint is +reached. +* `finish` [frame-number] \(or `fin`): execute until the selected stack frame +returns. If no frame number is given, the application will run until the +currently selected frame returns. The currently selected frame starts out the +most-recent frame or 0 if no frame positioning (e.g up, down or frame) has been +performed. If a frame number is given it will run until the specified frame +returns. ### Editing Two commands allow you to open code from the debugger into an editor: -* `edit [file:line]`: edit _file_ using the editor specified by the EDITOR environment variable. A specific _line_ can also be given. -* `tmate _n_` (abbreviated `tm`): open the current file in TextMate. It uses n-th frame if _n_ is specified. +* `edit [file:line]`: edit _file_ using the editor specified by the EDITOR +environment variable. A specific _line_ can also be given. ### Quitting -To exit the debugger, use the `quit` command (abbreviated `q`), or its alias `exit`. +To exit the debugger, use the `quit` command (abbreviated `q`), or its alias +`exit`. -A simple quit tries to terminate all threads in effect. Therefore your server will be stopped and you will have to start it again. +A simple quit tries to terminate all threads in effect. Therefore your server +will be stopped and you will have to start it again. ### Settings -The `debugger` gem can automatically show the code you're stepping through and reload it when you change it in an editor. Here are a few of the available options: - -* `set reload`: Reload source code when changed. -* `set autolist`: Execute `list` command on every breakpoint. -* `set listsize _n_`: Set number of source lines to list by default to _n_. -* `set forcestep`: Make sure the `next` and `step` commands always move to a new line +`byebug` has a few available options to tweak its behaviour: -You can see the full list by using `help set`. Use `help set _subcommand_` to learn about a particular `set` command. +* `set autoreload`: Reload source code when changed (default: true). +* `set autolist`: Execute `list` command on every breakpoint (default: true). +* `set listsize _n_`: Set number of source lines to list by default to _n_ +(default: 10) +* `set forcestep`: Make sure the `next` and `step` commands always move to a new +line. -TIP: You can save these settings in an `.rdebugrc` file in your home directory. The debugger reads these global settings when it starts. +You can see the full list by using `help set`. Use `help set _subcommand_` to +learn about a particular `set` command. -Here's a good start for an `.rdebugrc`: +TIP: You can save these settings in an `.byebugrc` file in your home directory. +The debugger reads these global settings when it starts. For example: ```bash -set autolist set forcestep set listsize 25 ``` @@ -671,35 +716,59 @@ set listsize 25 Debugging Memory Leaks ---------------------- -A Ruby application (on Rails or not), can leak memory - either in the Ruby code or at the C code level. +A Ruby application (on Rails or not), can leak memory - either in the Ruby code +or at the C code level. -In this section, you will learn how to find and fix such leaks by using tool such as Valgrind. +In this section, you will learn how to find and fix such leaks by using tool +such as Valgrind. ### Valgrind -[Valgrind](http://valgrind.org/) is a Linux-only application for detecting C-based memory leaks and race conditions. +[Valgrind](http://valgrind.org/) is a Linux-only application for detecting +C-based memory leaks and race conditions. -There are Valgrind tools that can automatically detect many memory management and threading bugs, and profile your programs in detail. For example, if a C extension in the interpreter calls `malloc()` but doesn't properly call `free()`, this memory won't be available until the app terminates. +There are Valgrind tools that can automatically detect many memory management +and threading bugs, and profile your programs in detail. For example, if a C +extension in the interpreter calls `malloc()` but doesn't properly call +`free()`, this memory won't be available until the app terminates. -For further information on how to install Valgrind and use with Ruby, refer to [Valgrind and Ruby](http://blog.evanweaver.com/articles/2008/02/05/valgrind-and-ruby/) by Evan Weaver. +For further information on how to install Valgrind and use with Ruby, refer to +[Valgrind and Ruby](http://blog.evanweaver.com/articles/2008/02/05/valgrind-and-ruby/) +by Evan Weaver. Plugins for Debugging --------------------- -There are some Rails plugins to help you to find errors and debug your application. Here is a list of useful plugins for debugging: - -* [Footnotes](https://github.com/josevalim/rails-footnotes) Every Rails page has footnotes that give request information and link back to your source via TextMate. -* [Query Trace](https://github.com/ntalbott/query_trace/tree/master) Adds query origin tracing to your logs. -* [Query Reviewer](https://github.com/nesquena/query_reviewer) This rails plugin not only runs "EXPLAIN" before each of your select queries in development, but provides a small DIV in the rendered output of each page with the summary of warnings for each query that it analyzed. -* [Exception Notifier](https://github.com/smartinez87/exception_notification/tree/master) Provides a mailer object and a default set of templates for sending email notifications when errors occur in a Rails application. -* [Better Errors](https://github.com/charliesome/better_errors) Replaces the standard Rails error page with a new one containing more contextual information, like source code and variable inspection. -* [RailsPanel](https://github.com/dejan/rails_panel) Chrome extension for Rails development that will end your tailing of development.log. Have all information about your Rails app requests in the browser - in the Developer Tools panel. Provides insight to db/rendering/total times, parameter list, rendered views and more. +There are some Rails plugins to help you to find errors and debug your +application. Here is a list of useful plugins for debugging: + +* [Footnotes](https://github.com/josevalim/rails-footnotes) Every Rails page has +footnotes that give request information and link back to your source via +TextMate. +* [Query Trace](https://github.com/ntalbott/query_trace/tree/master) Adds query +origin tracing to your logs. +* [Query Reviewer](https://github.com/nesquena/query_reviewer) This rails plugin +not only runs "EXPLAIN" before each of your select queries in development, but +provides a small DIV in the rendered output of each page with the summary of +warnings for each query that it analyzed. +* [Exception Notifier](https://github.com/smartinez87/exception_notification/tree/master) +Provides a mailer object and a default set of templates for sending email +notifications when errors occur in a Rails application. +* [Better Errors](https://github.com/charliesome/better_errors) Replaces the +standard Rails error page with a new one containing more contextual information, +like source code and variable inspection. +* [RailsPanel](https://github.com/dejan/rails_panel) Chrome extension for Rails +development that will end your tailing of development.log. Have all information +about your Rails app requests in the browser - in the Developer Tools panel. +Provides insight to db/rendering/total times, parameter list, rendered views and +more. References ---------- * [ruby-debug Homepage](http://bashdb.sourceforge.net/ruby-debug/home-page.html) * [debugger Homepage](https://github.com/cldwalker/debugger) +* [byebug Homepage](https://github.com/deivid-rodriguez/byebug) * [Article: Debugging a Rails application with ruby-debug](http://www.sitepoint.com/debug-rails-app-ruby-debug/) * [Ryan Bates' debugging ruby (revised) screencast](http://railscasts.com/episodes/54-debugging-ruby-revised) * [Ryan Bates' stack trace screencast](http://railscasts.com/episodes/24-the-stack-trace) -- cgit v1.2.3 From 3fe7b5f4a1edcbb9239a1587d2a565bc45c41f2e Mon Sep 17 00:00:00 2001 From: Parth Bharadiya Date: Thu, 10 Apr 2014 15:41:09 +0530 Subject: Correct factual error for page not found --- guides/source/upgrading_ruby_on_rails.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'guides') diff --git a/guides/source/upgrading_ruby_on_rails.md b/guides/source/upgrading_ruby_on_rails.md index 9fbe3313d2..da161f84c9 100644 --- a/guides/source/upgrading_ruby_on_rails.md +++ b/guides/source/upgrading_ruby_on_rails.md @@ -464,7 +464,7 @@ being used, you can update your form to use the `PUT` method instead: <%= form_for [ :update_name, @user ], method: :put do |f| %> ``` -For more on PATCH and why this change was made, see [this post](http://weblog.rubyonrails.org/2012/2/26/edge-rails-patch-is-the-new-primary-http-method-for-updates/) +For more on PATCH and why this change was made, see [this post](http://weblog.rubyonrails.org/2012/2/25/edge-rails-patch-is-the-new-primary-http-method-for-updates/) on the Rails blog. #### A note about media types -- cgit v1.2.3 From 3664e3a4307ab6877e593cc8b0f5103f94e49313 Mon Sep 17 00:00:00 2001 From: Juanito Fatas Date: Thu, 10 Apr 2014 22:44:47 +0800 Subject: [ci skip] Update code snippets to latest master (initialization.md). Also update the `server.run` example (Replace Mongrel with Puma). --- guides/source/initialization.md | 155 ++++++++++++++++++++++++++-------------- 1 file changed, 102 insertions(+), 53 deletions(-) (limited to 'guides') diff --git a/guides/source/initialization.md b/guides/source/initialization.md index ec3cec5c6f..ca5fcbbcbd 100644 --- a/guides/source/initialization.md +++ b/guides/source/initialization.md @@ -166,6 +166,7 @@ is called. COMMAND_WHITELIST = %(plugin generate destroy console server dbconsole application runner new version help) def run_command!(command) + command = parse_command(command) if COMMAND_WHITELIST.include?(command) send(command) else @@ -178,8 +179,7 @@ With the `server` command, Rails will further run the following code: ```ruby def set_application_directory! - Dir.chdir(File.expand_path('../../', APP_PATH)) unless - File.exist?(File.expand_path("config.ru")) + Dir.chdir(File.expand_path('../../', APP_PATH)) unless File.exist?(File.expand_path("config.ru")) end def server @@ -187,6 +187,8 @@ def server require_command!("server") Rails::Server.new.tap do |server| + # We need to require application after the server sets environment, + # otherwise the --environment option given to the server won't propagate. require APP_PATH Dir.chdir(Rails.application.root) server.start @@ -207,6 +209,7 @@ sets up the `Rails::Server` class. require 'fileutils' require 'optparse' require 'action_dispatch' +require 'rails' module Rails class Server < ::Rack::Server @@ -273,7 +276,7 @@ def parse_options(args) # http://www.meb.uni-bonn.de/docs/cgi/cl.html args.clear if ENV.include?("REQUEST_METHOD") - options.merge! opt_parser.parse! args + options.merge! opt_parser.parse!(args) options[:config] = ::File.expand_path(options[:config]) ENV["RACK_ENV"] = options[:environment] options @@ -284,13 +287,16 @@ With the `default_options` set to this: ```ruby def default_options + environment = ENV['RACK_ENV'] || 'development' + default_host = environment == 'development' ? 'localhost' : '0.0.0.0' + { - environment: ENV['RACK_ENV'] || "development", - pid: nil, - Port: 9292, - Host: "0.0.0.0", - AccessLog: [], - config: "config.ru" + :environment => environment, + :pid => nil, + :Port => 9292, + :Host => default_host, + :AccessLog => [], + :config => "config.ru" } end ``` @@ -348,6 +354,7 @@ private def print_boot_information ... puts "=> Run `rails server -h` for more startup options" + ... puts "=> Ctrl-C to shutdown server" unless options[:daemonize] end @@ -434,7 +441,11 @@ The `app` method here is defined like so: ```ruby def app - @app ||= begin + @app ||= options[:builder] ? build_app_from_string : build_app_and_options_from_config +end +... +private + def build_app_and_options_from_config if !::File.exist? options[:config] abort "configuration #{options[:config]} not found" end @@ -443,7 +454,10 @@ def app self.options.merge! options app end -end + + def build_app_from_string + Rack::Builder.new_from_string(self.options[:builder]) + end ``` The `options[:config]` value defaults to `config.ru` which contains this: @@ -459,8 +473,14 @@ run <%= app_const %> The `Rack::Builder.parse_file` method here takes the content from this `config.ru` file and parses it using this code: ```ruby -app = eval "Rack::Builder.new {( " + cfgfile + "\n )}.to_app", - TOPLEVEL_BINDING, config +app = new_from_string cfgfile, config + +... + +def self.new_from_string(builder_script, file="(rackup)") + eval "Rack::Builder.new {\n" + builder_script + "\n}.to_app", + TOPLEVEL_BINDING, file, 0 +end ``` The `initialize` method of `Rack::Builder` will take the block here and execute it within an instance of `Rack::Builder`. This is where the majority of the initialization process of Rails happens. The `require` line for `config/environment.rb` in `config.ru` is the first to run: @@ -473,11 +493,22 @@ require ::File.expand_path('../config/environment', __FILE__) This file is the common file required by `config.ru` (`rails server`) and Passenger. This is where these two ways to run the server meet; everything before this point has been Rack and Rails setup. -This file begins with requiring `config/application.rb`. +This file begins with requiring `config/application.rb`: + +```ruby +require File.expand_path('../application', __FILE__) +``` ### `config/application.rb` -This file requires `config/boot.rb`, but only if it hasn't been required before, which would be the case in `rails server` but **wouldn't** be the case with Passenger. +This file requires `config/boot.rb`: + +```ruby +require File.expand_path('../boot', __FILE__) +``` + +But only if it hasn't been required before, which would be the case in `rails server` +but **wouldn't** be the case with Passenger. Then the fun begins! @@ -498,11 +529,12 @@ This file is responsible for requiring all the individual frameworks of Rails: require "rails" %w( - active_record - action_controller - action_mailer - rails/test_unit - sprockets + active_record + action_controller + action_view + action_mailer + rails/test_unit + sprockets ).each do |framework| begin require "#{framework}/railtie" @@ -568,7 +600,7 @@ initializers (like building the middleware stack) are run last. The `railtie` initializers are the initializers which have been defined on the `Rails::Application` itself and are run between the `bootstrap` and `finishers`. -After this is done we go back to `Rack::Server` +After this is done we go back to `Rack::Server`. ### Rack: lib/rack/server.rb @@ -576,7 +608,11 @@ Last time we left when the `app` method was being defined: ```ruby def app - @app ||= begin + @app ||= options[:builder] ? build_app_from_string : build_app_and_options_from_config +end +... +private + def build_app_and_options_from_config if !::File.exist? options[:config] abort "configuration #{options[:config]} not found" end @@ -585,7 +621,10 @@ def app self.options.merge! options app end -end + + def build_app_from_string + Rack::Builder.new_from_string(self.options[:builder]) + end ``` At this point `app` is the Rails app itself (a middleware), and what @@ -611,40 +650,50 @@ server.run wrapped_app, options, &blk ``` At this point, the implementation of `server.run` will depend on the -server you're using. For example, if you were using Mongrel, here's what +server you're using. For example, if you were using Puma, here's what the `run` method would look like: ```ruby -def self.run(app, options={}) - server = ::Mongrel::HttpServer.new( - options[:Host] || '0.0.0.0', - options[:Port] || 8080, - options[:num_processors] || 950, - options[:throttle] || 0, - options[:timeout] || 60) - # Acts like Rack::URLMap, utilizing Mongrel's own path finding methods. - # Use is similar to #run, replacing the app argument with a hash of - # { path=>app, ... } or an instance of Rack::URLMap. - if options[:map] - if app.is_a? Hash - app.each do |path, appl| - path = '/'+path unless path[0] == ?/ - server.register(path, Rack::Handler::Mongrel.new(appl)) - end - elsif app.is_a? URLMap - app.instance_variable_get(:@mapping).each do |(host, path, appl)| - next if !host.nil? && !options[:Host].nil? && options[:Host] != host - path = '/'+path unless path[0] == ?/ - server.register(path, Rack::Handler::Mongrel.new(appl)) - end - else - raise ArgumentError, "first argument should be a Hash or URLMap" - end - else - server.register('/', Rack::Handler::Mongrel.new(app)) +... +DEFAULT_OPTIONS = { + :Host => '0.0.0.0', + :Port => 8080, + :Threads => '0:16', + :Verbose => false +} + +def self.run(app, options = {}) + options = DEFAULT_OPTIONS.merge(options) + + if options[:Verbose] + app = Rack::CommonLogger.new(app, STDOUT) end + + if options[:environment] + ENV['RACK_ENV'] = options[:environment].to_s + end + + server = ::Puma::Server.new(app) + min, max = options[:Threads].split(':', 2) + + puts "Puma #{::Puma::Const::PUMA_VERSION} starting..." + puts "* Min threads: #{min}, max threads: #{max}" + puts "* Environment: #{ENV['RACK_ENV']}" + puts "* Listening on tcp://#{options[:Host]}:#{options[:Port]}" + + server.add_tcp_listener options[:Host], options[:Port] + server.min_threads = min + server.max_threads = max yield server if block_given? - server.run.join + + begin + server.run.join + rescue Interrupt + puts "* Gracefully stopping, waiting for requests to finish" + server.stop(true) + puts "* Goodbye!" + end + end ``` @@ -654,4 +703,4 @@ the last piece of our journey in the Rails initialization process. This high level overview will help you understand when your code is executed and how, and overall become a better Rails developer. If you still want to know more, the Rails source code itself is probably the -best place to go next. +best place to go next. \ No newline at end of file -- cgit v1.2.3 From 16f481b28bb1299e5aa5c610ca4c90be8482edc7 Mon Sep 17 00:00:00 2001 From: Kyle Heironimus Date: Thu, 10 Apr 2014 14:58:36 -0500 Subject: Add after_commit/after_rollback to callback list Adding after_commit/after_rollback to list of callbacks in order helps explain the callback order as well as making it consistent with the API docs at http://api.rubyonrails.org/classes/ActiveRecord/Callbacks.html --- guides/source/active_record_callbacks.md | 3 +++ 1 file changed, 3 insertions(+) (limited to 'guides') diff --git a/guides/source/active_record_callbacks.md b/guides/source/active_record_callbacks.md index 667433285f..fbcce325ed 100644 --- a/guides/source/active_record_callbacks.md +++ b/guides/source/active_record_callbacks.md @@ -92,6 +92,7 @@ Here is a list with all the available Active Record callbacks, listed in the sam * `around_create` * `after_create` * `after_save` +* `after_commit/after_rollback` ### Updating an Object @@ -103,12 +104,14 @@ Here is a list with all the available Active Record callbacks, listed in the sam * `around_update` * `after_update` * `after_save` +* `after_commit/after_rollback` ### Destroying an Object * `before_destroy` * `around_destroy` * `after_destroy` +* `after_commit/after_rollback` WARNING. `after_save` runs both on create and update, but always _after_ the more specific callbacks `after_create` and `after_update`, no matter the order in which the macro calls were executed. -- cgit v1.2.3 From 8c1406cf256c0140748c98cd3c533afc504e0007 Mon Sep 17 00:00:00 2001 From: Akshay Vishnoi Date: Fri, 11 Apr 2014 01:27:44 +0530 Subject: [ci skip] Remove false documentation --- guides/source/active_support_core_extensions.md | 15 +-------------- 1 file changed, 1 insertion(+), 14 deletions(-) (limited to 'guides') diff --git a/guides/source/active_support_core_extensions.md b/guides/source/active_support_core_extensions.md index 5698dc0413..f08a85770f 100644 --- a/guides/source/active_support_core_extensions.md +++ b/guides/source/active_support_core_extensions.md @@ -964,20 +964,7 @@ NOTE: Defined in `active_support/core_ext/module/delegation.rb` There are cases where you need to define a method with `define_method`, but don't know whether a method with that name already exists. If it does, a warning is issued if they are enabled. No big deal, but not clean either. -The method `redefine_method` prevents such a potential warning, removing the existing method before if needed. Rails uses it in a few places, for instance when it generates an association's API: - -```ruby -redefine_method("#{reflection.name}=") do |new_value| - association = association_instance_get(reflection.name) - - if association.nil? || association.target != new_value - association = association_proxy_class.new(self, reflection) - end - - association.replace(new_value) - association_instance_set(reflection.name, new_value.nil? ? nil : association) -end -``` +The method `redefine_method` prevents such a potential warning, removing the existing method before if needed. NOTE: Defined in `active_support/core_ext/module/remove_method.rb` -- cgit v1.2.3 From 8834847a37398ec6413f5bd6099ef265e5240598 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?David=20Rodr=C3=ADguez=20de=20Dios?= Date: Fri, 11 Apr 2014 11:00:19 +0200 Subject: Minor fixes in the rails debugging guide --- guides/source/debugging_rails_applications.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) (limited to 'guides') diff --git a/guides/source/debugging_rails_applications.md b/guides/source/debugging_rails_applications.md index 2357399900..a4273d772b 100644 --- a/guides/source/debugging_rails_applications.md +++ b/guides/source/debugging_rails_applications.md @@ -308,7 +308,7 @@ For example: ```bash @posts = Post.all -(rdb:7) +(byebug:7) ``` Now it's time to explore and dig into your application. A good place to start is @@ -589,7 +589,7 @@ been executed yet. Use the `next` command to move on in the code: (byebug) next /PathTo/project/app/models/author.rb:12 @recent_comments -(rdb:1) var instance +(byebug:1) var instance @attributes = {"updated_at"=>"2008-07-31 12:46:10", "id"=>"1", "first_name"=>"Bob", "las... @attributes_cache = {} @comments = [] -- cgit v1.2.3 From 545afc150e4491a69d72d61864680b98dce5a7b7 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?David=20Rodr=C3=ADguez=20de=20Dios?= Date: Fri, 11 Apr 2014 13:55:42 +0200 Subject: Re-review the debugging guide. Tested on a brand new app to exactly match current byebug's behaviour. --- guides/source/debugging_rails_applications.md | 351 ++++++++++++++++---------- 1 file changed, 218 insertions(+), 133 deletions(-) (limited to 'guides') diff --git a/guides/source/debugging_rails_applications.md b/guides/source/debugging_rails_applications.md index a4273d772b..042ffa7d8d 100644 --- a/guides/source/debugging_rails_applications.md +++ b/guides/source/debugging_rails_applications.md @@ -283,20 +283,21 @@ As soon as your application calls the `byebug` method, the debugger will be started in a debugger shell inside the terminal window where you launched your application server, and you will be placed at the debugger's prompt `(byebug)`. Before the prompt, the code around the line that is about to be run will be -shown and the current line is marked by '=>'. Like this: +displayed and the current line will be marked by '=>'. Like this: ``` [1, 10] in /PathTo/project/app/controllers/posts_controller.rb - 1 class PostsController < ApplicationController - 2 # GET /posts - 3 # GET /posts.json - 4 def index - 5 byebug -=> 6 @posts = Post.all - 7 - 8 respond_to do |format| - 9 format.html # index.html.erb - 10 format.json { render json: @posts } + 3: + 4: # GET /posts + 5: # GET /posts.json + 6: def index + 7: byebug +=> 8: @posts = Post.find_recent + 9: + 10: respond_to do |format| + 11: format.html # index.html.erb + 12: format.json { render json: @posts } + (byebug) ``` @@ -307,8 +308,33 @@ processing the entire request. For example: ```bash -@posts = Post.all -(byebug:7) +=> Booting WEBrick +=> Rails 4.1.0 application starting in development on http://0.0.0.0:3000 +=> Run `rails server -h` for more startup options +=> Notice: server is listening on all interfaces (0.0.0.0). Consider using 127.0.0.1 (--binding option) +=> Ctrl-C to shutdown server +[2014-04-11 13:11:47] INFO WEBrick 1.3.1 +[2014-04-11 13:11:47] INFO ruby 2.1.1 (2014-02-24) [i686-linux] +[2014-04-11 13:11:47] INFO WEBrick::HTTPServer#start: pid=6370 port=3000 + + +Started GET "/" for 127.0.0.1 at 2014-04-11 13:11:48 +0200 + ActiveRecord::SchemaMigration Load (0.2ms) SELECT "schema_migrations".* FROM "schema_migrations" +Processing by PostsController#index as HTML + +[3, 12] in /PathTo/project/app/controllers/posts_controller.rb + 3: + 4: # GET /posts + 5: # GET /posts.json + 6: def index + 7: byebug +=> 8: @posts = Post.find_recent + 9: + 10: respond_to do |format| + 11: format.html # index.html.erb + 12: format.json { render json: @posts } + +(byebug) ``` Now it's time to explore and dig into your application. A good place to start is @@ -316,7 +342,8 @@ by asking the debugger for help. Type: `help` ``` (byebug) help -byebug 2.6.0 + +byebug 2.7.0 Type 'help ' for help on a specific command @@ -337,36 +364,41 @@ To see the previous ten lines you should type `list-` (or `l-`) ``` (byebug) l- + [1, 10] in /PathTo/project/app/controllers/posts_controller.rb 1 class PostsController < ApplicationController - 2 # GET /posts - 3 # GET /posts.json - 4 def index - 5 byebug - 6 @posts = Post.all - 7 - 8 respond_to do |format| - 9 format.html # index.html.erb - 10 format.json { render json: @posts } + 2 before_action :set_post, only: [:show, :edit, :update, :destroy] + 3 + 4 # GET /posts + 5 # GET /posts.json + 6 def index + 7 byebug + 8 @posts = Post.find_recent + 9 + 10 respond_to do |format| + ``` This way you can move inside the file, being able to see the code above and over -the line you added the `byebug` call. Finally, to see where you are in the code -again you can type `list=` +the line where you added the `byebug` call. Finally, to see where you are in +the code again you can type `list=` ``` (byebug) list= -[1, 10] in /PathTo/project/app/controllers/posts_controller.rb - 1 class PostsController < ApplicationController - 2 # GET /posts - 3 # GET /posts.json - 4 def index - 5 byebug -=> 6 @posts = Post.all - 7 - 8 respond_to do |format| - 9 format.html # index.html.erb - 10 format.json { render json: @posts } + +[3, 12] in /PathTo/project/app/controllers/posts_controller.rb + 3: + 4: # GET /posts + 5: # GET /posts.json + 6: def index + 7: byebug +=> 8: @posts = Post.find_recent + 9: + 10: respond_to do |format| + 11: format.html # index.html.erb + 12: format.json { render json: @posts } + +(byebug) ``` ### The Context @@ -387,33 +419,47 @@ then `backtrace` will supply the answer. ``` (byebug) where - #0 PostsController.index - at line /PathTo/project/app/controllers/posts_controller.rb:6 - #1 Kernel.send - at line /PathTo/project/vendor/rails/actionpack/lib/action_controller/base.rb:1175 - #2 ActionController::Base.perform_action_without_filters - at line /PathTo/project/vendor/rails/actionpack/lib/action_controller/base.rb:1175 - #3 ActionController::Filters::InstanceMethods.call_filters(chain#ActionController::Fil...,...) - at line /PathTo/project/vendor/rails/actionpack/lib/action_controller/filters.rb:617 +--> #0 PostsController.index + at /PathTo/project/test_app/app/controllers/posts_controller.rb:8 + #1 ActionController::ImplicitRender.send_action(method#String, *args#Array) + at /PathToGems/actionpack-4.1.0/lib/action_controller/metal/implicit_render.rb:4 + #2 AbstractController::Base.process_action(action#NilClass, *args#Array) + at /PathToGems/actionpack-4.1.0/lib/abstract_controller/base.rb:189 + #3 ActionController::Rendering.process_action(action#NilClass, *args#NilClass) + at /PathToGems/actionpack-4.1.0/lib/action_controller/metal/rendering.rb:10 ... ``` -You move anywhere you want in this trace (thus changing the context) by using -the `frame _n_` command, where _n_ is the specified frame number. +The current frame is marked with `-->`. You can move anywhere you want in this +trace (thus changing the context) by using the `frame _n_` command, where _n_ is +the specified frame number. If you do that, `byebug` will display your new +context. ``` (byebug) frame 2 -#2 ActionController::Base.perform_action_without_filters - at line /PathTo/project/vendor/rails/actionpack/lib/action_controller/base.rb:1175 + +[184, 193] in /PathToGems/actionpack-4.1.0/lib/abstract_controller/base.rb + 184: # is the intended way to override action dispatching. + 185: # + 186: # Notice that the first argument is the method to be dispatched + 187: # which is *not* necessarily the same as the action name. + 188: def process_action(method_name, *args) +=> 189: send_action(method_name, *args) + 190: end + 191: + 192: # Actually call the method associated with the action. Override + 193: # this method if you wish to change how action methods are called, + +(byebug) ``` The available variables are the same as if you were running the code line by line. After all, that's what debugging is. -Moving up and down the stack frame: You can use `up [n]` (`u` for abbreviated) -and `down [n]` commands in order to change the context _n_ frames up or down the -stack respectively. _n_ defaults to one. Up in this case is towards -higher-numbered stack frames, and down is towards lower-numbered stack frames. +You can also use `up [n]` (`u` for abbreviated) and `down [n]` commands in order +to change the context _n_ frames up or down the stack respectively. _n_ defaults +to one. Up in this case is towards higher-numbered stack frames, and down is +towards lower-numbered stack frames. ### Threads @@ -441,12 +487,22 @@ This example shows how you can print the instance_variables defined within the current context: ``` -@posts = Post.all +[3, 12] in /PathTo/project/app/controllers/posts_controller.rb + 3: + 4: # GET /posts + 5: # GET /posts.json + 6: def index + 7: byebug +=> 8: @posts = Post.find_recent + 9: + 10: respond_to do |format| + 11: format.html # index.html.erb + 12: format.json { render json: @posts } + (byebug) instance_variables -["@_response", "@action_name", "@url", "@_session", "@_cookies", - "@performed_render", "@_flash", "@template", "@_params", - "@before_filter_chain_aborted", "@request_origin", "@_headers", - "@performed_redirect", "@_request"] +[:@_action_has_layout, :@_routes, :@_headers, :@_status, :@_request, + :@_response, :@_env, :@_prefixes, :@_lookup_context, :@_action_name, + :@_response_body, :@marked_for_same_origin_verification, :@_config] ``` As you may have figured out, all of the variables that you can access from a @@ -456,11 +512,19 @@ command later in this guide). ``` (byebug) next -Processing PostsController#index (for 127.0.0.1 at 2008-09-04 19:51:34) [GET] - Session ID: BAh7BiIKZmxhc2hJQzonQWN0aW9uQ29udHJvbGxlcjo6Rmxhc2g6OkZsYXNoSGFzaHsABjoKQHVzZWR7AA==--b16e91b992453a8cc201694d660147bba8b0fd0e - Parameters: {"action"=>"index", "controller"=>"posts"} -/PathToProject/posts_controller.rb:8 -respond_to do |format| +[5, 14] in /PathTo/project/app/controllers/posts_controller.rb + 5 # GET /posts.json + 6 def index + 7 byebug + 8 @posts = Post.find_recent + 9 +=> 10 respond_to do |format| + 11 format.html # index.html.erb + 12 format.json { render json: @posts } + 13 end + 14 end + 15 +(byebug) ``` And then ask again for the instance_variables: @@ -477,31 +541,37 @@ TIP: You can also step into **irb** mode with the command `irb` (of course!). This way an irb session will be started within the context you invoked it. But be warned: this is an experimental feature. -The `var` method is the most convenient way to show variables and their values: +The `var` method is the most convenient way to show variables and their values. +Let's let `byebug` to help us with it. ``` -var -(byebug) v[ar] const show constants of object -(byebug) v[ar] g[lobal] show global variables -(byebug) v[ar] i[nstance] show instance variables of object -(byebug) v[ar] l[ocal] show local variables +(byebug) help var +v[ar] cl[ass] show class variables of self +v[ar] const show constants of object +v[ar] g[lobal] show global variables +v[ar] i[nstance] show instance variables of object +v[ar] l[ocal] show local variables ``` This is a great way to inspect the values of the current context variables. For -example: +example, to check that we have no local variables currently defined. ``` (byebug) var local - __dbg_verbose_save => false +(byebug) ``` You can also inspect for an object method this way: ``` (byebug) var instance Post.new -@attributes = {"updated_at"=>nil, "body"=>nil, "title"=>nil, "published"=>nil, "created_at"... +@_start_transaction_state = {} +@aggregation_cache = {} +@association_cache = {} +@attributes = {"id"=>nil, "created_at"=>nil, "updated_at"=>nil} @attributes_cache = {} -@new_record = true +@changed_attributes = nil +... ``` TIP: The commands `p` (print) and `pp` (pretty print) can be used to evaluate @@ -511,8 +581,8 @@ You can use also `display` to start watching variables. This is a good way of tracking the values of a variable while the execution goes on. ``` -(byebug) display @recent_comments -1: @recent_comments = +(byebug) display @posts +1: @posts = nil ``` The variables inside the displaying list will be printed with their values after @@ -528,80 +598,80 @@ execution. Use `step` (abbreviated `s`) to continue running your program until the next logical stopping point and return control to the debugger. -TIP: You can also use `step+ n` and `step- n` to move forward or backward `n` -steps respectively. - You may also use `next` which is similar to step, but function or method calls -that appear within the line of code are executed without stopping. As with -`step`, you may use plus sign to move _n_ steps. +that appear within the line of code are executed without stopping. + +TIP: You can also use `step n` or `next n` to move forwards `n` steps at once. The difference between `next` and `step` is that `step` stops at the next line of code executed, doing just a single step, while `next` moves to the next line without descending inside methods. -For example, consider this block of code with an included `byebug` statement: +For example, consider the following situation: ```ruby -class Author < ActiveRecord::Base - has_one :editorial - has_many :comments +Started GET "/" for 127.0.0.1 at 2014-04-11 13:39:23 +0200 +Processing by PostsController#index as HTML + +[1, 8] in /home/davidr/Proyectos/test_app/app/models/post.rb + 1: class Post < ActiveRecord::Base + 2: + 3: def self.find_recent(limit = 10) + 4: byebug +=> 5: where('created_at > ?', 1.week.ago).limit(limit) + 6: end + 7: + 8: end - def find_recent_comments(limit = 10) - byebug - @recent_comments ||= comments.where("created_at > ?", 1.week.ago).limit(limit) - end -end +(byebug) ``` +If we use `next`, we want go deep inside method calls. Instead, byebug will go +to the next line within the same context. In this case, this is the last line of +the method, so `byebug` will jump to next next line of the previous frame. + ``` -$ rails console -Loading development environment (Rails 4.0.0) ->> author = Author.first -=> # ->> author.find_recent_comments -/PathTo/project/app/models/author.rb:11 -) -[2, 9] in /PathTo/project/app/models/author.rb - 2 has_one :editorial - 3 has_many :comments - 4 - 5 def find_recent_comments(limit = 10) - 6 byebug -=> 7 @recent_comments ||= comments.where("created_at > ?", 1.week.ago).limit(limit) - 8 end - 9 end +(byebug) next +Next went up a frame because previous frame finished + +[4, 13] in /PathTo/project/test_app/app/controllers/posts_controller.rb + 4: # GET /posts + 5: # GET /posts.json + 6: def index + 7: @posts = Post.find_recent + 8: +=> 9: respond_to do |format| + 10: format.html # index.html.erb + 11: format.json { render json: @posts } + 12: end + 13: end + (byebug) ``` -You are at the end of the line, but... was this line executed? You can inspect -the instance variables. +If we use `step` in the same situation, we will literally go the next ruby +instruction to be executed. In this case, the activesupport's `week` method. ``` -(byebug) var instance -@attributes = {"updated_at"=>"2008-07-31 12:46:10", "id"=>"1", "first_name"=>"Bob", "las... -@attributes_cache = {} -``` +(byebug) step -`@recent_comments` hasn't been defined yet, so it's clear that this line hasn't -been executed yet. Use the `next` command to move on in the code: +[50, 59] in /PathToGems/activesupport-4.1.0/lib/active_support/core_ext/numeric/time.rb + 50: ActiveSupport::Duration.new(self * 24.hours, [[:days, self]]) + 51: end + 52: alias :day :days + 53: + 54: def weeks +=> 55: ActiveSupport::Duration.new(self * 7.days, [[:days, self * 7]]) + 56: end + 57: alias :week :weeks + 58: + 59: def fortnights -``` -(byebug) next -/PathTo/project/app/models/author.rb:12 -@recent_comments -(byebug:1) var instance -@attributes = {"updated_at"=>"2008-07-31 12:46:10", "id"=>"1", "first_name"=>"Bob", "las... -@attributes_cache = {} -@comments = [] -@recent_comments = [] +(byebug) ``` -Now you can see that the `@comments` relationship was loaded and -`@recent_comments` defined because the line was executed. - -If you want to go deeper into the stack trace you can move single steps -through your calling methods and into Rails code. This is one of the best ways -to find bugs in your code, or perhaps in Ruby or Rails. +This is one of the best ways to find bugs in your code, or perhaps in Ruby on +Rails. ### Breakpoints @@ -620,18 +690,33 @@ the debugger. _expression_ works the same way as with file:line. +For example, in the previous situation + ``` -(byebug:5) break 10 -Breakpoint 1 file /PathTo/project/vendor/rails/actionpack/lib/action_controller/filters.rb, line 10 +[4, 13] in /PathTo/project/app/controllers/posts_controller.rb + 4: # GET /posts + 5: # GET /posts.json + 6: def index + 7: @posts = Post.find_recent + 8: +=> 9: respond_to do |format| + 10: format.html # index.html.erb + 11: format.json { render json: @posts } + 12: end + 13: end + +(byebug) break 11 +Created breakpoint 1 at /PathTo/project/app/controllers/posts_controller.rb:11 + ``` Use `info breakpoints _n_` or `info break _n_` to list breakpoints. If you supply a number, it lists that breakpoint. Otherwise it lists all breakpoints. ``` -(byebug:5) info breakpoints +(byebug) info breakpoints Num Enb What - 1 y at filters.rb:10 +1 y at /PathTo/project/app/controllers/posts_controller.rb:11 ``` To delete breakpoints: use the command `delete _n_` to remove the breakpoint @@ -639,8 +724,8 @@ number _n_. If no number is specified, it deletes all breakpoints that are currently active. ``` -(byebug:5) delete 1 -(byebug:5) info breakpoints +(byebug) delete 1 +(byebug) info breakpoints No breakpoints. ``` -- cgit v1.2.3 From 075a1e21fa59433976dd6860b775a280db10f606 Mon Sep 17 00:00:00 2001 From: Akshay Vishnoi Date: Fri, 11 Apr 2014 17:57:16 +0530 Subject: Add more test case for #demodulize, Improve documentation --- guides/source/active_support_core_extensions.md | 3 +++ 1 file changed, 3 insertions(+) (limited to 'guides') diff --git a/guides/source/active_support_core_extensions.md b/guides/source/active_support_core_extensions.md index f08a85770f..834c94e2ec 100644 --- a/guides/source/active_support_core_extensions.md +++ b/guides/source/active_support_core_extensions.md @@ -1631,6 +1631,9 @@ Given a string with a qualified constant name, `demodulize` returns the very con "Product".demodulize # => "Product" "Backoffice::UsersController".demodulize # => "UsersController" "Admin::Hotel::ReservationUtils".demodulize # => "ReservationUtils" +"::Inflections".demodulize # => "Inflections" +"".demodulize # => "" + ``` Active Record for example uses this method to compute the name of a counter cache column: -- cgit v1.2.3 From f612c2b0526e326eb6c25a7bbf375ac3ac793a3c Mon Sep 17 00:00:00 2001 From: Matthew Draper Date: Fri, 11 Apr 2014 02:28:35 +0930 Subject: Move assets precompile (and version) to an initializer sprockets-rails 2.1 needs the precompile list to be available in all environments. --- guides/source/asset_pipeline.md | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) (limited to 'guides') diff --git a/guides/source/asset_pipeline.md b/guides/source/asset_pipeline.md index 9338f570a7..d688bb7b4e 100644 --- a/guides/source/asset_pipeline.md +++ b/guides/source/asset_pipeline.md @@ -709,17 +709,17 @@ JS/CSS is excluded, as well as raw JS/CSS files; for example, `.coffee` and `.scss` files are **not** automatically included as they compile to JS/CSS. If you have other manifests or individual stylesheets and JavaScript files to -include, you can add them to the `precompile` array in `config/application.rb`: +include, you can add them to the `precompile` array in `config/initializers/assets.rb`: ```ruby -config.assets.precompile += ['admin.js', 'admin.css', 'swfObject.js'] +Rails.application.config.assets.precompile += ['admin.js', 'admin.css', 'swfObject.js'] ``` Or, you can opt to precompile all assets with something like this: ```ruby -# config/application.rb -config.assets.precompile << Proc.new do |path| +# config/initializers/assets.rb +Rails.application.config.assets.precompile << Proc.new do |path| if path =~ /\.(css|js)\z/ full_path = Rails.application.assets.resolve(path).to_path app_assets_path = Rails.root.join('app', 'assets').to_path -- cgit v1.2.3 From aca64fed43d0c9eafabaf6a36c749796783c899c Mon Sep 17 00:00:00 2001 From: Jano Suchal Date: Fri, 11 Apr 2014 15:19:37 +0200 Subject: Be explicit about allowed constraint values, fixes #14702 --- guides/source/routing.md | 2 ++ 1 file changed, 2 insertions(+) (limited to 'guides') diff --git a/guides/source/routing.md b/guides/source/routing.md index eef618f28d..921658a71e 100644 --- a/guides/source/routing.md +++ b/guides/source/routing.md @@ -694,6 +694,8 @@ namespace :admin do end ``` +NOTE: Request constraints work by calling a method on the Request object with the same name as the hash key and then compare the return value with the hash value. Therefore, constraint values should match the corresponding Request object method return type. For example: `constraints: { subdomain: 'api' }` will match an `api` subdomain as expected, however using a symbol `constraints: { subdomain: :api }` will not, because `request.subdomain` returns `'api'` as a String. + ### Advanced Constraints If you have a more advanced constraint, you can provide an object that responds to `matches?` that Rails should use. Let's say you wanted to route all users on a blacklist to the `BlacklistController`. You could do: -- cgit v1.2.3 From 4e9c0b7874b0c01891f79af9ca2dd110a0529c50 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Rafael=20Mendon=C3=A7a=20Fran=C3=A7a?= Date: Fri, 11 Apr 2014 13:39:37 -0300 Subject: Fix version indicator on guides and link to Rails 4.0 [ci skip] --- guides/source/_welcome.html.erb | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) (limited to 'guides') diff --git a/guides/source/_welcome.html.erb b/guides/source/_welcome.html.erb index 9fd930963a..7e39f761f2 100644 --- a/guides/source/_welcome.html.erb +++ b/guides/source/_welcome.html.erb @@ -10,10 +10,13 @@

<% else %>

- These are the new guides for Rails 4.0 based on <%= @version %>. + These are the new guides for Rails 4.1 based on <%= @version %>. These guides are designed to make you immediately productive with Rails, and to help you understand how all of the pieces fit together.

<% end %> +

+ The guides for Rails 4.0.x are available at http://guides.rubyonrails.org/v4.0.4/. +

The guides for Rails 3.2.x are available at http://guides.rubyonrails.org/v3.2.17/.

-- cgit v1.2.3 From 73bfb510119e7552378949d635164010e3d5abe2 Mon Sep 17 00:00:00 2001 From: Vipul A M Date: Sat, 12 Apr 2014 12:46:04 +0530 Subject: Change links to 37signals and svn blog to point to new destinations. [ci skip] --- guides/source/caching_with_rails.md | 4 ++-- guides/source/credits.html.erb | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) (limited to 'guides') diff --git a/guides/source/caching_with_rails.md b/guides/source/caching_with_rails.md index e898d75d1a..b6423dd44e 100644 --- a/guides/source/caching_with_rails.md +++ b/guides/source/caching_with_rails.md @@ -30,13 +30,13 @@ config.action_controller.perform_caching = true Page caching is a Rails mechanism which allows the request for a generated page to be fulfilled by the webserver (i.e. Apache or nginx), without ever having to go through the Rails stack at all. Obviously, this is super-fast. Unfortunately, it can't be applied to every situation (such as pages that need authentication) and since the webserver is literally just serving a file from the filesystem, cache expiration is an issue that needs to be dealt with. -INFO: Page Caching has been removed from Rails 4. See the [actionpack-page_caching gem](https://github.com/rails/actionpack-page_caching). See [DHH's key-based cache expiration overview](http://37signals.com/svn/posts/3113-how-key-based-cache-expiration-works) for the newly-preferred method. +INFO: Page Caching has been removed from Rails 4. See the [actionpack-page_caching gem](https://github.com/rails/actionpack-page_caching). See [DHH's key-based cache expiration overview](http://signalvnoise.com/posts/3113-how-key-based-cache-expiration-works) for the newly-preferred method. ### Action Caching Page Caching cannot be used for actions that have before filters - for example, pages that require authentication. This is where Action Caching comes in. Action Caching works like Page Caching except the incoming web request hits the Rails stack so that before filters can be run on it before the cache is served. This allows authentication and other restrictions to be run while still serving the result of the output from a cached copy. -INFO: Action Caching has been removed from Rails 4. See the [actionpack-action_caching gem](https://github.com/rails/actionpack-action_caching). See [DHH's key-based cache expiration overview](http://37signals.com/svn/posts/3113-how-key-based-cache-expiration-works) for the newly-preferred method. +INFO: Action Caching has been removed from Rails 4. See the [actionpack-action_caching gem](https://github.com/rails/actionpack-action_caching). See [DHH's key-based cache expiration overview](http://signalvnoise.com/posts/3113-how-key-based-cache-expiration-works) for the newly-preferred method. ### Fragment Caching diff --git a/guides/source/credits.html.erb b/guides/source/credits.html.erb index 7c6858fa2c..8767fbecce 100644 --- a/guides/source/credits.html.erb +++ b/guides/source/credits.html.erb @@ -64,7 +64,7 @@ Oscar Del Ben is a software engineer at Wi <% end %> <%= author('Pratik Naik', 'lifo') do %> - Pratik Naik is a Ruby on Rails developer at 37signals and also a member of the Rails core team. He maintains a blog at has_many :bugs, :through => :rails and has a semi-active twitter account. + Pratik Naik is a Ruby on Rails developer at Basecamp and also a member of the Rails core team. He maintains a blog at has_many :bugs, :through => :rails and has a semi-active twitter account. <% end %> <%= author('Emilio Tagua', 'miloops') do %> -- cgit v1.2.3 From 80d0dd53caeb55dffcbf3e86b3707d170899f035 Mon Sep 17 00:00:00 2001 From: Robin Dupret Date: Sat, 12 Apr 2014 20:10:15 +0200 Subject: Fix a few typos [ci skip] This is a follow up to 545afc15. --- guides/source/debugging_rails_applications.md | 26 +++++++++++++------------- 1 file changed, 13 insertions(+), 13 deletions(-) (limited to 'guides') diff --git a/guides/source/debugging_rails_applications.md b/guides/source/debugging_rails_applications.md index 042ffa7d8d..b067d9efb7 100644 --- a/guides/source/debugging_rails_applications.md +++ b/guides/source/debugging_rails_applications.md @@ -210,7 +210,7 @@ logger.tagged("BCX") { logger.tagged("Jason") { logger.info "Stuff" } } # Logs " ``` ### Impact of Logs on Performance -Logging will always have a small impact on performance of your rails app, +Logging will always have a small impact on performance of your rails app, particularly when logging to disk.However, there are a few subtleties: Using the `:debug` level will have a greater performance penalty than `:fatal`, @@ -224,20 +224,20 @@ Another potential pitfall is that if you have many calls to `Logger` like this logger.debug "Person attributes hash: #{@person.attributes.inspect}" ``` -In the above example, There will be a performance impact even if the allowed -output level doesn't include debug. The reason is that Ruby has to evaluate -these strings, which includes instantiating the somewhat heavy `String` object +In the above example, There will be a performance impact even if the allowed +output level doesn't include debug. The reason is that Ruby has to evaluate +these strings, which includes instantiating the somewhat heavy `String` object and interpolating the variables, and which takes time. -Therefore, it's recommended to pass blocks to the logger methods, as these are -only evaluated if the output level is the same or included in the allowed level +Therefore, it's recommended to pass blocks to the logger methods, as these are +only evaluated if the output level is the same or included in the allowed level (i.e. lazy loading). The same code rewritten would be: ```ruby logger.debug {"Person attributes hash: #{@person.attributes.inspect}"} ``` -The contents of the block, and therefore the string interpolation, is only -evaluated if debug is enabled. This performance savings is only really +The contents of the block, and therefore the string interpolation, is only +evaluated if debug is enabled. This performance savings is only really noticeable with large amounts of logging, but it's a good practice to employ. Debugging with the `byebug` gem @@ -380,7 +380,7 @@ To see the previous ten lines you should type `list-` (or `l-`) ``` This way you can move inside the file, being able to see the code above and over -the line where you added the `byebug` call. Finally, to see where you are in +the line where you added the `byebug` call. Finally, to see where you are in the code again you can type `list=` ``` @@ -464,7 +464,7 @@ towards lower-numbered stack frames. ### Threads The debugger can list, stop, resume and switch between running threads by using -the command `thread` (or the abbreviated `th`). This command has a handful of +the `thread` command (or the abbreviated `th`). This command has a handful of options: * `thread` shows the current thread. @@ -483,7 +483,7 @@ code. Any expression can be evaluated in the current context. To evaluate an expression, just type it! -This example shows how you can print the instance_variables defined within the +This example shows how you can print the instance variables defined within the current context: ``` @@ -626,7 +626,7 @@ Processing by PostsController#index as HTML (byebug) ``` -If we use `next`, we want go deep inside method calls. Instead, byebug will go +If we use `next`, we want go deep inside method calls. Instead, byebug will go to the next line within the same context. In this case, this is the last line of the method, so `byebug` will jump to next next line of the previous frame. @@ -731,7 +731,7 @@ No breakpoints. You can also enable or disable breakpoints: -* `enable breakpoints`: allow a list _breakpoints_ or all of them if no list is +* `enable breakpoints`: allow a _breakpoints_ list or all of them if no list is specified, to stop your program. This is the default state when you create a breakpoint. * `disable breakpoints`: the _breakpoints_ will have no effect on your program. -- cgit v1.2.3 From 7782fdcf2b093d977f4cdcba884bcab07aad25ef Mon Sep 17 00:00:00 2001 From: Afshin Mokhtari Date: Sat, 12 Apr 2014 17:43:23 -0700 Subject: Missing 'are' in note - [ci skip] This is in the note at the end of Section 2: Controller Naming Convention. [ci skip] --- guides/source/action_controller_overview.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'guides') diff --git a/guides/source/action_controller_overview.md b/guides/source/action_controller_overview.md index 0f46ba8698..d788d13ac9 100644 --- a/guides/source/action_controller_overview.md +++ b/guides/source/action_controller_overview.md @@ -34,7 +34,7 @@ The naming convention of controllers in Rails favors pluralization of the last w Following this convention will allow you to use the default route generators (e.g. `resources`, etc) without needing to qualify each `:path` or `:controller`, and keeps URL and path helpers' usage consistent throughout your application. See [Layouts & Rendering Guide](layouts_and_rendering.html) for more details. -NOTE: The controller naming convention differs from the naming convention of models, which expected to be named in singular form. +NOTE: The controller naming convention differs from the naming convention of models, which are expected to be named in singular form. Methods and Actions -- cgit v1.2.3 From 2ddbe87e7acc324ce7e0a4784c4d10b79cc49a40 Mon Sep 17 00:00:00 2001 From: Marcel Morgan Date: Sat, 12 Apr 2014 08:31:00 -0500 Subject: Update documentation to use Rails.application instead References to ``AppName::Application` removed in favour of ``Rails.application`` as generated with a new rails 4.1 app. [ci skip] --- guides/code/getting_started/Rakefile | 2 +- guides/code/getting_started/config.ru | 2 +- guides/code/getting_started/config/environment.rb | 2 +- guides/code/getting_started/config/environments/development.rb | 2 +- guides/code/getting_started/config/environments/production.rb | 2 +- guides/code/getting_started/config/environments/test.rb | 2 +- guides/code/getting_started/config/initializers/secret_token.rb | 2 +- guides/code/getting_started/config/initializers/session_store.rb | 2 +- guides/code/getting_started/config/routes.rb | 2 +- guides/source/action_controller_overview.md | 6 +++--- guides/source/getting_started.md | 2 +- guides/source/i18n.md | 2 +- guides/source/initialization.md | 2 +- guides/source/rails_on_rack.md | 9 ++++----- guides/source/routing.md | 4 ++-- 15 files changed, 21 insertions(+), 22 deletions(-) (limited to 'guides') diff --git a/guides/code/getting_started/Rakefile b/guides/code/getting_started/Rakefile index 05de8bb536..ba6b733dd2 100644 --- a/guides/code/getting_started/Rakefile +++ b/guides/code/getting_started/Rakefile @@ -3,4 +3,4 @@ require File.expand_path('../config/application', __FILE__) -Blog::Application.load_tasks +Rails.application.load_tasks diff --git a/guides/code/getting_started/config.ru b/guides/code/getting_started/config.ru index ddf869e921..5bc2a619e8 100644 --- a/guides/code/getting_started/config.ru +++ b/guides/code/getting_started/config.ru @@ -1,4 +1,4 @@ # This file is used by Rack-based servers to start the application. require ::File.expand_path('../config/environment', __FILE__) -run Blog::Application +run Rails.application diff --git a/guides/code/getting_started/config/environment.rb b/guides/code/getting_started/config/environment.rb index e7e341c960..ee8d90dc65 100644 --- a/guides/code/getting_started/config/environment.rb +++ b/guides/code/getting_started/config/environment.rb @@ -2,4 +2,4 @@ require File.expand_path('../application', __FILE__) # Initialize the Rails application. -Blog::Application.initialize! +Rails.application.initialize! diff --git a/guides/code/getting_started/config/environments/development.rb b/guides/code/getting_started/config/environments/development.rb index 7e5692b08b..ae9ffe209a 100644 --- a/guides/code/getting_started/config/environments/development.rb +++ b/guides/code/getting_started/config/environments/development.rb @@ -1,4 +1,4 @@ -Blog::Application.configure do +Rails.application.configure do # Settings specified here will take precedence over those in config/application.rb. # In the development environment your application's code is reloaded on diff --git a/guides/code/getting_started/config/environments/production.rb b/guides/code/getting_started/config/environments/production.rb index 8c514e065e..c8ae858574 100644 --- a/guides/code/getting_started/config/environments/production.rb +++ b/guides/code/getting_started/config/environments/production.rb @@ -1,4 +1,4 @@ -Blog::Application.configure do +Rails.application.configure do # Settings specified here will take precedence over those in config/application.rb. # Code is not reloaded between requests. diff --git a/guides/code/getting_started/config/environments/test.rb b/guides/code/getting_started/config/environments/test.rb index 34ab1530d1..680d0b9e06 100644 --- a/guides/code/getting_started/config/environments/test.rb +++ b/guides/code/getting_started/config/environments/test.rb @@ -1,4 +1,4 @@ -Blog::Application.configure do +Rails.application.configure do # Settings specified here will take precedence over those in config/application.rb. # The test environment is used exclusively to run your application's diff --git a/guides/code/getting_started/config/initializers/secret_token.rb b/guides/code/getting_started/config/initializers/secret_token.rb index aaf57731be..c2a549c299 100644 --- a/guides/code/getting_started/config/initializers/secret_token.rb +++ b/guides/code/getting_started/config/initializers/secret_token.rb @@ -9,4 +9,4 @@ # Make sure your secret_key_base is kept private # if you're sharing your code publicly. -Blog::Application.config.secret_key_base = 'e8aab50cec8a06a75694111a4cbaf6e22fc288ccbc6b268683aae7273043c69b15ca07d10c92a788dd6077a54762cbfcc55f19c3459f7531221b3169f8171a53' +Rails.application.config.secret_key_base = 'e8aab50cec8a06a75694111a4cbaf6e22fc288ccbc6b268683aae7273043c69b15ca07d10c92a788dd6077a54762cbfcc55f19c3459f7531221b3169f8171a53' diff --git a/guides/code/getting_started/config/initializers/session_store.rb b/guides/code/getting_started/config/initializers/session_store.rb index 3b2ca93ab9..1b9fa324d4 100644 --- a/guides/code/getting_started/config/initializers/session_store.rb +++ b/guides/code/getting_started/config/initializers/session_store.rb @@ -1,3 +1,3 @@ # Be sure to restart your server when you modify this file. -Blog::Application.config.session_store :cookie_store, key: '_blog_session' +Rails.application.config.session_store :cookie_store, key: '_blog_session' diff --git a/guides/code/getting_started/config/routes.rb b/guides/code/getting_started/config/routes.rb index 0155b613a3..65d273b58d 100644 --- a/guides/code/getting_started/config/routes.rb +++ b/guides/code/getting_started/config/routes.rb @@ -1,4 +1,4 @@ -Blog::Application.routes.draw do +Rails.application.routes.draw do resources :posts do resources :comments end diff --git a/guides/source/action_controller_overview.md b/guides/source/action_controller_overview.md index d788d13ac9..ee2b00aedb 100644 --- a/guides/source/action_controller_overview.md +++ b/guides/source/action_controller_overview.md @@ -364,21 +364,21 @@ If you need a different session storage mechanism, you can change it in the `con # Use the database for sessions instead of the cookie-based default, # which shouldn't be used to store highly confidential information # (create the session table with "rails g active_record:session_migration") -# YourApp::Application.config.session_store :active_record_store +# Rails.application.config.session_store :active_record_store ``` Rails sets up a session key (the name of the cookie) when signing the session data. These can also be changed in `config/initializers/session_store.rb`: ```ruby # Be sure to restart your server when you modify this file. -YourApp::Application.config.session_store :cookie_store, key: '_your_app_session' +Rails.application.config.session_store :cookie_store, key: '_your_app_session' ``` You can also pass a `:domain` key and specify the domain name for the cookie: ```ruby # Be sure to restart your server when you modify this file. -YourApp::Application.config.session_store :cookie_store, key: '_your_app_session', domain: ".example.com" +Rails.application.config.session_store :cookie_store, key: '_your_app_session', domain: ".example.com" ``` Rails sets up (for the CookieStore) a secret key used for signing the session data. This can be changed in `config/secrets.yml` diff --git a/guides/source/getting_started.md b/guides/source/getting_started.md index c54c9efe94..bafb75c668 100644 --- a/guides/source/getting_started.md +++ b/guides/source/getting_started.md @@ -344,7 +344,7 @@ resource. Here's what `config/routes.rb` should look like after the _article resource_ is declared. ```ruby -Blog::Application.routes.draw do +Rails.application.routes.draw do resources :articles diff --git a/guides/source/i18n.md b/guides/source/i18n.md index 6bd033f0de..466ffe7907 100644 --- a/guides/source/i18n.md +++ b/guides/source/i18n.md @@ -309,7 +309,7 @@ You most probably have something like this in one of your applications: ```ruby # config/routes.rb -Yourapp::Application.routes.draw do +Rails.application.routes.draw do root to: "home#index" end ``` diff --git a/guides/source/initialization.md b/guides/source/initialization.md index ca5fcbbcbd..77f3615ca0 100644 --- a/guides/source/initialization.md +++ b/guides/source/initialization.md @@ -558,7 +558,7 @@ The rest of `config/application.rb` defines the configuration for the initialized. When `config/application.rb` has finished loading Rails and defined the application namespace, we go back to `config/environment.rb`, where the application is initialized. For example, if the application was called -`Blog`, here we would find `Blog::Application.initialize!`, which is +`Blog`, here we would find `Rails.application.initialize!`, which is defined in `rails/application.rb` ### `railties/lib/rails/application.rb` diff --git a/guides/source/rails_on_rack.md b/guides/source/rails_on_rack.md index 9c92cf3aea..b1b4c8fa4e 100644 --- a/guides/source/rails_on_rack.md +++ b/guides/source/rails_on_rack.md @@ -27,10 +27,9 @@ Rails on Rack ### Rails Application's Rack Object -`ApplicationName::Application` is the primary Rack application object of a Rails +`Rails.application` is the primary Rack application object of a Rails application. Any Rack compliant web server should be using -`ApplicationName::Application` object to serve a Rails -application. `Rails.application` refers to the same application object. +`Rails.application` object to serve a Rails application. ### `rails server` @@ -141,7 +140,7 @@ use ActionDispatch::ParamsParser use Rack::Head use Rack::ConditionalGet use Rack::ETag -run MyApp::Application.routes +run Rails.application.routes ``` The default middlewares shown here (and some others) are each summarized in the [Internal Middlewares](#internal-middleware-stack) section, below. @@ -201,7 +200,7 @@ use ActionDispatch::Static use # use Rack::Runtime ... -run Blog::Application.routes +run Rails.application.routes ``` If you want to remove session related middleware, do the following: diff --git a/guides/source/routing.md b/guides/source/routing.md index 921658a71e..0783bce442 100644 --- a/guides/source/routing.md +++ b/guides/source/routing.md @@ -711,7 +711,7 @@ class BlacklistConstraint end end -TwitterClone::Application.routes.draw do +Rails.application.routes.draw do get '*path', to: 'blacklist#index', constraints: BlacklistConstraint.new end @@ -720,7 +720,7 @@ end You can also specify constraints as a lambda: ```ruby -TwitterClone::Application.routes.draw do +Rails.application.routes.draw do get '*path', to: 'blacklist#index', constraints: lambda { |request| Blacklist.retrieve_ips.include?(request.remote_ip) } end -- cgit v1.2.3 From 982a19edc932caa3d58394b0f7076a191eff5a54 Mon Sep 17 00:00:00 2001 From: Juanito Fatas Date: Sun, 13 Apr 2014 23:56:59 +0800 Subject: [ci skip] Use plain underscore instead of "\_". --- guides/source/3_0_release_notes.md | 2 +- guides/source/3_2_release_notes.md | 2 +- guides/source/association_basics.md | 2 +- guides/source/security.md | 4 ++-- 4 files changed, 5 insertions(+), 5 deletions(-) (limited to 'guides') diff --git a/guides/source/3_0_release_notes.md b/guides/source/3_0_release_notes.md index dd81ec58f9..2d4be0cda7 100644 --- a/guides/source/3_0_release_notes.md +++ b/guides/source/3_0_release_notes.md @@ -294,7 +294,7 @@ NOTE. The old style `map` commands still work as before with a backwards compati Deprecations * The catch all route for non-REST applications (`/:controller/:action/:id`) is now commented out. -* Routes :path\_prefix no longer exists and :name\_prefix now automatically adds "\_" at the end of the given value. +* Routes `:path_prefix` no longer exists and `:name_prefix` now automatically adds "_" at the end of the given value. More Information: * [The Rails 3 Router: Rack it Up](http://yehudakatz.com/2009/12/26/the-rails-3-router-rack-it-up/) diff --git a/guides/source/3_2_release_notes.md b/guides/source/3_2_release_notes.md index ce811a583b..cdcde67869 100644 --- a/guides/source/3_2_release_notes.md +++ b/guides/source/3_2_release_notes.md @@ -187,7 +187,7 @@ Action Pack Rails will use `layouts/single_car` when a request comes in `:show` action, and use `layouts/application` (or `layouts/cars`, if exists) when a request comes in for any other actions. -* `form\_for` is changed to use `#{action}\_#{as}` as the css class and id if `:as` option is provided. Earlier versions used `#{as}\_#{action}`. +* `form_for` is changed to use `#{action}_#{as}` as the css class and id if `:as` option is provided. Earlier versions used `#{as}_#{action}`. * `ActionController::ParamsWrapper` on Active Record models now only wrap `attr_accessible` attributes if they were set. If not, only the attributes returned by the class method `attribute_names` will be wrapped. This fixes the wrapping of nested attributes by adding them to `attr_accessible`. diff --git a/guides/source/association_basics.md b/guides/source/association_basics.md index 5ec6ae0f21..df38bd7321 100644 --- a/guides/source/association_basics.md +++ b/guides/source/association_basics.md @@ -571,7 +571,7 @@ If you create an association some time after you build the underlying model, you If you create a `has_and_belongs_to_many` association, you need to explicitly create the joining table. Unless the name of the join table is explicitly specified by using the `:join_table` option, Active Record creates the name by using the lexical order of the class names. So a join between customer and order models will give the default join table name of "customers_orders" because "c" outranks "o" in lexical ordering. -WARNING: The precedence between model names is calculated using the `<` operator for `String`. This means that if the strings are of different lengths, and the strings are equal when compared up to the shortest length, then the longer string is considered of higher lexical precedence than the shorter one. For example, one would expect the tables "paper\_boxes" and "papers" to generate a join table name of "papers\_paper\_boxes" because of the length of the name "paper\_boxes", but it in fact generates a join table name of "paper\_boxes\_papers" (because the underscore '\_' is lexicographically _less_ than 's' in common encodings). +WARNING: The precedence between model names is calculated using the `<` operator for `String`. This means that if the strings are of different lengths, and the strings are equal when compared up to the shortest length, then the longer string is considered of higher lexical precedence than the shorter one. For example, one would expect the tables "paper_boxes" and "papers" to generate a join table name of "papers_paper_boxes" because of the length of the name "paper_boxes", but it in fact generates a join table name of "paper_boxes_papers" (because the underscore '_' is lexicographically _less_ than 's' in common encodings). Whatever the name, you must manually generate the join table with an appropriate migration. For example, consider these associations: diff --git a/guides/source/security.md b/guides/source/security.md index 9603fb4a4d..15b28664b7 100644 --- a/guides/source/security.md +++ b/guides/source/security.md @@ -151,7 +151,7 @@ The most effective countermeasure is to _issue a new session identifier_ and dec reset_session ``` -If you use the popular RestfulAuthentication plugin for user management, add reset\_session to the SessionsController#create action. Note that this removes any value from the session, _you have to transfer them to the new session_. +If you use the popular RestfulAuthentication plugin for user management, add reset_session to the SessionsController#create action. Note that this removes any value from the session, _you have to transfer them to the new session_. Another countermeasure is to _save user-specific properties in the session_, verify them every time a request comes in, and deny access, if the information does not match. Such properties could be the remote IP address or the user agent (the web browser name), though the latter is less user-specific. When saving the IP address, you have to bear in mind that there are Internet service providers or large organizations that put their users behind proxies. _These might change over the course of a session_, so these users will not be able to use your application, or only in a limited way. @@ -314,7 +314,7 @@ def sanitize_filename(filename) end ``` -A significant disadvantage of synchronous processing of file uploads (as the attachment\_fu plugin may do with images), is its _vulnerability to denial-of-service attacks_. An attacker can synchronously start image file uploads from many computers which increases the server load and may eventually crash or stall the server. +A significant disadvantage of synchronous processing of file uploads (as the attachment_fu plugin may do with images), is its _vulnerability to denial-of-service attacks_. An attacker can synchronously start image file uploads from many computers which increases the server load and may eventually crash or stall the server. The solution to this is best to _process media files asynchronously_: Save the media file and schedule a processing request in the database. A second process will handle the processing of the file in the background. -- cgit v1.2.3 From 0debba8899c64f80526ad08c9f535a40c808ece6 Mon Sep 17 00:00:00 2001 From: Nick Borromeo Date: Sun, 13 Apr 2014 12:01:45 -0700 Subject: Disable assest cache store in docs [ci skip] --- guides/source/asset_pipeline.md | 8 ++++++++ 1 file changed, 8 insertions(+) (limited to 'guides') diff --git a/guides/source/asset_pipeline.md b/guides/source/asset_pipeline.md index d688bb7b4e..d3dc790500 100644 --- a/guides/source/asset_pipeline.md +++ b/guides/source/asset_pipeline.md @@ -1041,6 +1041,14 @@ cache store. config.assets.cache_store = :memory_store, { size: 32.megabytes } ``` +To disable the assets cache store: + +```ruby +config.assets.configure do |env| + env.cache = ActiveSupport::Cache.lookup_store(:null_store) +end +``` + Adding Assets to Your Gems -------------------------- -- cgit v1.2.3 From 0e9fab5ff5c43d6f1c6b0eb8d0b1f988b499ebef Mon Sep 17 00:00:00 2001 From: Christopher Owen Date: Mon, 14 Apr 2014 12:06:59 +1000 Subject: - Fix lingering reference to `:text` instead of the newer `:plain` - Section references `form_tag` instead of the `form_for` used in the example --- guides/source/getting_started.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) (limited to 'guides') diff --git a/guides/source/getting_started.md b/guides/source/getting_started.md index bafb75c668..1ae7397696 100644 --- a/guides/source/getting_started.md +++ b/guides/source/getting_started.md @@ -612,7 +612,7 @@ def create end ``` -The `render` method here is taking a very simple hash with a key of `text` and +The `render` method here is taking a very simple hash with a key of `plain` and value of `params[:article].inspect`. The `params` method is the object which represents the parameters (or fields) coming in from the form. The `params` method returns an `ActiveSupport::HashWithIndifferentAccess` object, which @@ -1136,7 +1136,7 @@ The `method: :patch` option tells Rails that we want this form to be submitted via the `PATCH` HTTP method which is the HTTP method you're expected to use to **update** resources according to the REST protocol. -The first parameter of the `form_tag` can be an object, say, `@article` which would +The first parameter of `form_for` can be an object, say, `@article` which would cause the helper to fill in the form with the fields of the object. Passing in a symbol (`:article`) with the same name as the instance variable (`@article`) also automagically leads to the same behavior. This is what is happening here. More details -- cgit v1.2.3 From 1497529d05c8c5e66d9bad9b990b042442266136 Mon Sep 17 00:00:00 2001 From: ZENATI YASSINE Date: Mon, 14 Apr 2014 15:55:11 +0200 Subject: [ci skip] Added link to ruby-lang.org installation. --- guides/source/getting_started.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'guides') diff --git a/guides/source/getting_started.md b/guides/source/getting_started.md index 1ae7397696..36bbd1187c 100644 --- a/guides/source/getting_started.md +++ b/guides/source/getting_started.md @@ -99,7 +99,7 @@ ruby 2.0.0p353 ``` If you don't have Ruby installed have a look at -[ruby-lang.org](https://www.ruby-lang.org/en/downloads/) for possible ways to +[ruby-lang.org](https://www.ruby-lang.org/en/installation/) for possible ways to install Ruby on your platform. Many popular UNIX-like OSes ship with an acceptable version of SQLite3. Windows -- cgit v1.2.3